您需要添加三个额外的步骤:
首先,您需要将 JSON 映射转换为字符串(使用 json.encode)
然后,如果您想将其作为 application/x-www-form-urlencoded 发送,则需要对其进行 Uri 编码。
最后,您需要为要发布的参数命名。
例如(注意,这里使用的是dart:io HttpClient,但基本一样):
Future<HttpClientResponse> foo() async {
Map<String, dynamic> jsonMap = {
'homeTeam': {'team': 'Team A'},
'awayTeam': {'team': 'Team B'},
};
String jsonString = json.encode(jsonMap); // 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.post(_host, _port, '/a/b/c');
// it's polite to send the body length to the server
request.headers.set('Content-Length', bodyBytes.length.toString());
// todo add other headers here
request.add(bodyBytes);
return await request.close();
}
以上是dart:io版本(当然你可以在Flutter中使用)
如果您想坚持使用package:http 版本,那么您需要稍微调整一下您的地图。 body 必须是 Map<String, String>。你需要决定你想要什么作为你的 POST 参数。你想要两个:主队和客队?或者一个,比如说,teamJson?
这段代码
Map<String, String> body = {
'name': 'doodle',
'color': 'blue',
'homeTeam': json.encode(
{'team': 'Team A'},
),
'awayTeam': json.encode(
{'team': 'Team B'},
),
};
Response r = await post(
url,
body: body,
);
在电线上产生这个
name=doodle&color=blue&homeTeam=%7B%22team%22%3A%22Team+A%22%7D&awayTeam=%7B%22team%22%3A%22Team+B%22%7D
或者,这个
Map<String, String> body = {
'name': 'doodle',
'color': 'blue',
'teamJson': json.encode({
'homeTeam': {'team': 'Team A'},
'awayTeam': {'team': 'Team B'},
}),
};
Response r = await post(
url,
body: body,
);
在电线上产生这个
name=doodle&color=blue&teamJson=%7B%22homeTeam%22%3A%7B%22team%22%3A%22Team+A%22%7D%2C%22awayTeam%22%3A%7B%22team%22%3A% 22队+B%22%7D%7D
package:http 客户端负责:对 Uri.encodeQueryComponent 进行编码、utf8 编码(注意这是默认值,因此无需指定)并在 Content-Length 标头中发送长度。您仍然必须进行 json 编码。