【问题标题】:Flutter POST request body not sentFlutter POST 请求正文未发送
【发布时间】:2019-05-16 10:53:41
【问题描述】:

我想用以下代码在 Flutter 中发出一个 post 请求:

// Body: {"email": "example@email.com", "pass": "passw0rd"}

Future<dynamic> post(String url, var body) async {
  var response = await http.post(url, body: body);
  final String res = response.body;
  return res;
}

// That's not the full code. I removed some lines because they are useless for this thread.
// Most of them are only some debug outputs or conditional statements

问题是我的发布请求不包括我的请求正文。我在我的服务器上检查了一些输出。

【问题讨论】:

  • 尝试将请求发送到httpbin.org/post,这将回显请求。也许您缺少请求标头。您可以使用 curl 或 Postman 执行有效的帖子吗?

标签: dart flutter


【解决方案1】:

您只需在发送前对正文进行编码:

import 'dart:convert';
...

var bodyEncoded = json.encode(body);
var response = await http.post(url, body: bodyEncoded , headers: {
  "Accept": "application/json"
},);

【讨论】:

  • 感谢您的帮助。我还必须在标题中添加 "Content-Type": "application/x-www-form-urlencoded" 以使其正常工作。
  • 对我来说是headers: {"Content-Type": "application/json"} :) 另见stackoverflow.com/questions/27574740/…
猜你喜欢
  • 1970-01-01
  • 2018-05-26
  • 1970-01-01
  • 2021-03-12
  • 2016-07-03
  • 1970-01-01
  • 2019-08-15
  • 2020-02-12
  • 1970-01-01
相关资源
最近更新 更多