While fetching a URL in on the client (dart:html
) is straightforward, the server side (dart:io
) doesn't have the handy getString
method.
How do I simply load a URL document as a String?
While fetching a URL in on the client (dart:html
) is straightforward, the server side (dart:io
) doesn't have the handy getString
method.
How do I simply load a URL document as a String?
This will help:
import "dart:io";
import "dart:async";
import "dart:convert";
Future<String> fetch(String url) {
var completer = new Completer();
var client = new HttpClient();
client.getUrl(Uri.parse(url))
.then((request) {
// Just call close on the request to send it.
return request.close();
})
.then((response) {
// Process the response through the UTF-8 decoder.
response.transform(const Utf8Decoder()).join().then(completer.complete);
});
return completer.future;
}
You would use this method/function like this:
fetch("http://www.google.com/").then(print);
This gets the job done, but please note that this is not a robust solution. On the other hand, if you're doing anything more than a command-line script, you'll probably need more than this anyway.
Use the
http
package andread
function that returns the response body as a String: