您需要添加三个附加步骤:
首先,您需要将JSON映射转换为字符串(使用json.encode)
如果您想要将其作为application/x-www-form-urlencode发送,则需要对其进行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
版本的(当然,您也可以在FIFTER中使用它)
如果你想坚持使用package:http
版本,那么你需要稍微调整一下你的 map .body
号一定是Map<String, String>
号.你需要决定你想要什么作为你的POST参数.你想要两个吗:HomeTeam和AwayTeam?或者一个,比方说,team Json?
此代码
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&; colored颜色 =蓝色和蓝色;主队=%7B%22team%22%3A%22team+A%22%7D&;awayTeam=%7B%22团队%22%3A%22团队+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%22Team+B%22%7D%7D
package:http
客户端负责:对Uri进行编码.encodeQueryComponent,utf8编码(注意这是默认值,因此无需指定),并在Content length标头中发送长度.您仍然必须进行json编码.