从HttpClientResponse检索响应主体 [英] Retrieving the response body from an HttpClientResponse

查看:197
本文介绍了从HttpClientResponse检索响应主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Dart服务器应用程序编写一些测试,并且我一直在使用HttpClient类(以及相关的HttpClientRequest和HttpClientResponse类向服务器发出测试请求(请注意,我正在使用这些类,因为我需要dart:io包来运行服务器,所以我也不能导入dart:html。到目前为止,这一过程进展顺利,而且我已经能够编写测试来检查服务器是否返回正确的HTTP状态代码的响应。我用来进行这些测试调用的代码基础如下:

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 classes to make test requests to the server (note that I'm using these classes because I need the dart:io package for running the server, so I can't also import dart:html). This has been going fairly well so far, and I've been able to write tests to check that the server is returning responses with the correct HTTP Status code. The base of the code I've been using to make these test calls is as follows:

Future<HttpClientResponse> makeServerRequest(String method, Uri uri, [String jsonData]) async {
  HttpClient client = new HttpClient();
  HttpClientRequest request = await client.openUrl(method, uri);
  request.write(jsonData);
  return request.close();
}

现在我需要写在这可以确保响应的主体(不仅是状态码)是正确的。问题是我似乎找不到任何可以实际访问HttpClient *类中的响应正文的内容。到目前为止,我能找到的最接近的是 HttpClientResponse.contentLength 属性,但这仅告诉我响应主体有多大,而不是实际内容。

Now I need to write a test that makes sure that the body of the response, not just the status code, is correct. The problem is that I can't seem to find anything that allows me to actually access the response body in the HttpClient* classes. The closest I've been able to find so far is the HttpClientResponse.contentLength property, but that only tells me how big the response body is, and isn't the actual content.

如何检索这些请求的响应主体?或者,如果您做不到,还有其他方法可以在服务器端应用程序上发出请求,以便读取响应吗?

How do I retrieve the response body from these requests? Or, if you aren't able to, is there some other way I can make the requests on a server side application so I can read the responses?

推荐答案

HttpClientResponse 对象是 Stream ,因此您可以使用 listen()方法:

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

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

您还可以使用 dart:convert 解析数据。以下示例将响应内容读取为字符串:

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;
}

这篇关于从HttpClientResponse检索响应主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆