Flutter POST 请求正文未发送

Kea*_*Hie 5 dart flutter

我想使用以下代码在 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
Run Code Online (Sandbox Code Playgroud)

问题是我的帖子请求不包括我的请求正文。我用服务器上的一些输出检查了这一点。

die*_*per 8

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

import 'dart:convert';
...

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

  • 对我来说,它是 `headers: {"Content-Type": "application/json"}` :) 另请参阅 /sf/ask/1930231831/因达蒂奥 (3认同)
  • 谢谢您的帮助。我还必须在标题中添加 "Content-Type": "application/x-www-form-urlencoded" 以使其工作。 (2认同)