You are currently viewing Best Dart and Flutter HTTP Packages

Best Dart and Flutter HTTP Packages

HTTP stands for HyperText Transfer Protocol. It is the underlying protocol used by the World Wide Web for document transmission. As a protocol it does the following main roles:

  1. Definition of how messages are formatted and transmitted.
  2. Defininition of the actions Web servers and browsers should take in response to various commands.

Majority of Programming languages therefore do include packages that allow for HTTP communication and Dart is no exception. In this piece we want to look at some of the packages, standard or third party packages currently available that allow us write apps that utilize this protocol.

(a). http.dart

This is a standard dart package containing APIs that allow us easily consume HTTP resources. These APIs are composable,Future-based and platform independent.

http can be used while building a:

  1. General Purpose Dart Application e.g server, terminal
  2. Flutter Application
  3. Web Application

How to Install http

Add it as a dependency in your pubspec.yaml

dependencies:
  http: ^0.12.0+2

Then for dart:

$ pub get

Or for flutter:

$ flutter pub get

How to Use

First import it by adding the following line:

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

Now we have the http object that we can easily use, but first prepare a URL pointing to a location of the web resource we are targeting:

var url = 'https://yoururl.com/test/create';

Then utilize the http object to perform your request:

var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});

You can then print our the response code and body:

print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');

Here's a one line example to read and print out a txt file from a webserver:

print(await http.read('http://example.com/foobar.txt'));

Making Multiple Requests

Dart's http package allows you to keep a connection open so as to utilize it for making multiple HTTP requests to the same server. You use the Client object to achieve this. However make sure to close the connection when done to release the occupied resources.

var client = new http.Client();
try {
  var uriResponse = await client.post('http://example.com/whatsit/create',
      body: {'name': 'doodle', 'color': 'blue'});
  print(await client.get(uriResponse.bodyFields['uri']));
} finally {
  client.close();
}

Read more.

(b). http_auth

http_auth is a standard dart package that acts as a middleware for HTTP authentication (Basic/Digest). http_auth depends on:

No. Package Role
1. http A composable, Future-based library for making HTTP requests.
2, crypto A set of cryptographic hashing functions implemented in pure Dart.
3. convert Has encoders and decoders for converting between different data representations.

http_auth can be used while building a:

  1. General Purpose Dart Application e.g server, terminal
  2. Flutter Application
  3. Web Application

But what is a middleware?

A middleware with respect to HTTP is a term used to refer to a mechanism involving adding cross cutting operations or filters against HTTP requests entering your application. For example these operations can be:

  1. Authentication
  2. Logging
  3. Gzip compression

The details may be different in different programming languages and frameworks. For example in Dart, Nodejs, Rails, Laravel we use the term middleware. In Java Servlets the term filters is used while C# calls them delegate handlers.

Installing http_auth

Go to your pubspec.yaml and add the following:

dependencies:
  http_auth: ^0.2.6

Then for dart:

$ pub get

And for flutter:

$ flutter pub get

How to use http_auth

Add import in your code:

import 'package:http_auth/http_auth.dart';

Basic Authentication

Basic Authentication is the simplest form of HTTP Resource Acess access control. It's built into HTTP protocol.

With this authentication clients sends HTTP requests with Authorization Header containing the word Basic word followed by a space and a base64-encoded string username:password.

Here is how to perform basic authentication in Dart:

    import 'package:http_auth/http_auth.dart';
    main() async {
      var client = http_auth.BasicAuthClient('user', 'passwd');
      var response = client.get('http://httpbin.org/basic-auth/user/passwd');
    }

Digest Authentication

The second form of Authentication is a Digest Authentication.

Through this a HTTP Request from a potential user is received by a network server and then sent to a domain controller. The domain controller sends a special key, called a digest session key, to the server that received the original request. The user must then produce a response, which is encrypted and transmitted to the server. If the user's response is of the correct form, the server grants the user access to the network, Web site or requested resources for a single session.

Here is an example of digest authentication in Dart:

    import 'package:http_auth/http_auth.dart';
    main() async {
      var client = http_auth.DigestAuthClient('user', 'passwd');
      var response = client.get('http://httpbin.org/digest-auth/auth/user/passwd');
    }

The above examples are all asynchronous. However you can also perform synchronous operation:

import 'package:http_auth/http_auth.dart';
main() {
  var client = new DigestAuthClient("user", "passwd");
  final url = 'http://httpbin.org/digest-auth/auth/user/passwd';
  client.get(url).then((r) => print(r.body));
}

Read more.

(c). http_multi_server

This is an implementation of dart:io's HttpServer that wraps multiple servers and forwards methods to all of them. It's useful for serving the same application on multiple network interfaces while still having a unified wy of acontrolling the servers. In particular, it supports serving on both the IPv4 and IPv6 loopback addresses using HttpMultiServer.loopback.

It depends on:

No. Package Role
1. async Contains utility classes in the style of dart:async to work with asynchronous computations.

http_multi_server can be used while building a:

  1. General Purpose Dart Application e.g server, terminal
  2. Flutter Application

How To Install

In your pubspec.yaml:

dependencies:
  http_multi_server: ^2.1.0

Then:

$ flutter pub get

Or:

$ pub get

How to Use

Add import:

import 'package:http_multi_server/http_multi_server.dart';

Here's an example:

import 'package:http_multi_server/http_multi_server.dart';
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as shelf_io;
void main() {
  // Both http://127.0.0.1:8080 and http://[::1]:8080 will be bound to the same
  // server.
  HttpMultiServer.loopback(8080).then((server) {
    shelf_io.serveRequests(server, (request) {
      return new shelf.Response.ok("Hello, world!");
    });
  });
}

Download Code.

Leave a Reply