Retrieving the response body from an HttpClientResponse

The HttpClientResponse object is a Stream, so you can just read it with the listen() method:

response.listen((List<int> data) {
  //data as bytes
});

You can also use the codecs from dart:convert to parse the data. The following example reads the response contents to a String:

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

Future<String> readResponse(HttpClientResponse response) {
  final completer = Completer<String>();
  final contents = StringBuffer();
  response.transform(utf8.decoder).listen((data) {
    contents.write(data);
  }, onDone: () => completer.complete(contents.toString()));
  return completer.future;
}

Low level

Here is the await for version of collecting the response stream. It's a little more compact than using a completer.

Future<String> readResponse(HttpClientResponse response) async {
  final contents = StringBuffer();
  await for (var data in response.transform(utf8.decoder)) {
    contents.write(data);
  }
  return contents.toString();
}

You should wrap it in a try catch block to handle errors.

High level

Most of the time from the client side you would use the http library instead:

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

Response response = await get(url);
String content = response.body;

See this article for more details.

Tags:

Dart