flutter - 发布请求后如何处理响应 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());
}
我如何得到这个请求的响应?
解决方案
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
推荐阅读
- django-rest-framework - 字段验证在序列化程序中不起作用
- reactjs - 将 Webpack 从 v4 迁移到 v5 后,我的反应应用程序未在 IE11 中运行
- build - 为什么在构建 OpenWrt 时会以交互方式询问我一个选择?
- python - 在 VSC 上运行 python 失败
- mysql - Tableau 关系数据模型
- linux - qdiscs“附加”到什么?
- python - Join() method and tuples in Python
- python - 在带有 python 3.6 的 conda 环境中在 R 中安装 XML 在 Ubuntu 20.04 上失败
- django - 根据外键统计对象
- reactjs - Chakra UI createIcon() 抛出“无效的钩子调用”错误