Http classes

The dart:io library provides classes that command-line apps can use for accessing HTTP resources, as well as running HTTP servers.

The following are class mainly used in writing HTTP clients & servers.

  1. HttpClient
  2. HttpServer

HttpClient

The HttpClient class helps you connect to HTTP resources.

  1. You can use to set headers,
  2. Use HTTP methods.
  3. Read and write data.

Note:

HttpClient only works with Dart command-line and Server-side application.

The HttpClient class does not work in browser-based apps. When programming in the browser, use the dart:html HttpRequest class.

To use the HttpClient you must import it, dart:io library.

import 'dart:io';

The following code snippet shows how to connect with http resources.

import 'dart:io';
import 'dart:convert';

Future main() async {
  var url = Uri.parse('http://localhost:8080');

  var httpClient = HttpClient();

  var request = await httpClient.getUrl(url);

  var response = await request.close();

  var data = await utf8.decoder.bind(response).toList();

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

  httpClient.close();
}

HttpServer

The HttpServer class provides the low-level functionality for building web servers.

  1. You can match request handlers,
  2. Set headers,
  3. Stream data more.

To use the HttpServer you must import it, dart:io library.

import 'dart:io';

The following sample web server returns simple text information.

  1. This server listens on port 8080 and address 127.0.0.1 (localhost).
  2. Responding to requests for the path /.
  3. Returns simple text information
  4. For any other path, the response is status code 404 (page not found).
import 'dart:io';

void processRequest(HttpRequest request) {
  final response = request.response;

  if (request.uri.path == '/') {
    response
      ..headers.contentType = ContentType(
        'text',
        'plain',
      )
      ..write('Hello from the server');
  } else {
    response.statusCode = HttpStatus.notFound;
  }

  response.close();
}

Future main() async {

  final requests = await HttpServer.bind('localhost', 8080);

  print('Server running: http://localhost:8080');

  await for (var request in requests) {
    processRequest(request);
  }
}

Run: <http://localhost:8080>