Retrieving the response body from an HttpClientResponse

前端 未结 2 1139
时光说笑
时光说笑 2021-01-04 11:53

I\'m trying to write some tests for my Dart server application, and I\'ve been using the HttpClient class (along with the related HttpClientRequest and HttpClientResponse cl

2条回答
  •  难免孤独
    2021-01-04 12:31

    Low level

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

    Future 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.

提交回复
热议问题