首页 > 解决方案 > 发布请求后如何处理响应 dart httpClient

问题描述

所以我在发出 post 请求时遇到了颤振 http 包的问题,​​所以我使用了 dart HttpClient。我根据某处描述的内容提出了发布请求,但在获得回复时遇到问题。这是我的代码

 Future<HttpClientResponse> submit() async {
 print('start');
  Map<String, dynamic> data = { 'title' : 'My first post' };
  String jsonString = json.encode(data); // encode map to json
  String paramName = 'param'; // give the post param a name
  String formBody = paramName + '=' + Uri.encodeQueryComponent(jsonString);
  List<int> bodyBytes = utf8.encode(formBody); // utf8 encode
  HttpClientRequest request =
      await HttpClient().postUrl(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
  // it's polite to send the body length to the server
  request.headers.set('Content-Length', bodyBytes.length.toString());
  request.headers.set('Content-Type', 'application/json');
  request.add(bodyBytes);
  print('done');
  return await (request.close());
}

我如何得到这个请求的响应?

标签: flutterdart

解决方案


      HttpClientResponse response = await request.close();
      response.transform(utf8.decoder).listen((contents) {
        print(data); // <- response content is here
      });

这将返回 HttpCLientResponse,更多信息https://api.dartlang.org/stable/2.6.1/dart-io/HttpClient-class.html


推荐阅读