How do I fetch URL from a Dart server (dart:io)?

414 views Asked by At

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?

3

There are 3 answers

0
Shailen Tuli On BEST ANSWER

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);
}
1
filiph On

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.

0
Günter Zöchbauer On

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));
}