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?
Use the http
package and read
function that returns the response body as a String:
import 'package:http/http.dart' as http;
void main() {
http.read("http://httpbin.org/").then(print);
}
This should work on the server
import 'package:http/http.dart' as http;
void main(List<String> args) {
http.get("http://www.google.com").then((http.Response e) => print(e.statusCode));
}
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.