Example HTTP GET request using Dart IO lib

Free lines Dart 1 revisions 272 10 months ago 10 months ago
import 'dart:io';
import 'dart:convert';

void main() async {
  final host = 'jsonplaceholder.typicode.com';
  final path = '/posts/1';

  HttpClientRequest request = await new HttpClient().get(host, 80, path);
  HttpClientResponse response = await request.close(); // request.close() returns the response and ends connection
  response.transform(utf8.decoder).listen(print); // Pipe stuff to print function

This is a minimalistic example of how you can use HttpClient to send an HTTP GET request and read back the response.

As you've already guessed, you can do .post instead of .get for a POST request. With a POST request you use things like this to send some data:

HttpClientRequest request = await new HttpClient().post(host, 80, path)
  ..headers.contentType = ContentType.json