3
votes

I realized that currently there are at least three "official" Dart libraries that allow me to perform a HTTP request. What is more, three of those libraries (dart:io (class HttpClient), package:http and dart:html) have each a different, incompatible API.

As of today, package:html does not offer this functionality, but on its GitHub page I found it aims for 100% API compatibility with dart:html, so these methods will be added there eventually.

Which package provides the most future proof and platform independent API to issue a HTTP request in Dart?

Is it package:http?

import 'package:http/http.dart' as http;

var url = "http://example.com";
http.get(url)
    .then((response) {
  print("Response status: ${response.statusCode}");
  print("Response body: ${response.body}");
});

Is it dart:html/package:html?

import 'dart:html';

HttpRequest.request('/example.json')
  .then((response) {
      print("Response status: ${response.status}");
      print("Response body: ${response.response}");
});

Or dart:io?

import 'dart:io';

var client = new HttpClient();
client.getUrl(Uri.parse("http://www.example.com/"))
    .then((HttpClientRequest request) {
      // Optionally set up headers...
      // Optionally write to the request object...
      // Then call close.
      ...
      return request.close();
    })
    .then((HttpClientResponse response) {
      print("Response status: ${response.statusCode}");
      print("Response body:");
      response.transform(UTF8.decoder).listen((contents) {
        print(contents);
      });
    });

Let's say I want to cover Android too. That adds package:sky in the mix as well (https://github.com/domokit/sky_sdk/). I admit that this is not "official" Google library.

import 'package:sky/framework/net/fetch.dart';

Response response = await fetch('http://example.com');
print(response.bodyAsString());

What is (going to be) a regular product is https://www.youtube.com/watch?v=t8xdEO8LyL8. I wonder what their HTTP Request story is going to be. Something tells me it will be yet another different beast from all we have seen so far.

1

1 Answers

6
votes

The html package is a HTML parser which allows to work with HTML server side. I wouldn't expect it to get some HttpRequest capabilities.

The http package aims to provide a unified API for client and server Dart code. The API in dart:html is only a wrapper over the API the browser provides. The HttpRequest API in dart:io was built without browser restrictions and thus deviates from dart:html. package:http provides an unified API which delegates to dart:html when run in the browser and to dart:io when run on the server.

I think package:http is future proof and cross-platform and should be a good fit for your requirements.