您需要添加三个附加步骤:首先,您需要将json映射转换为String(使用json.enpre),然后,如果要将其作为application /
x-www-form-urlenpred发送,则需要对其进行Uri编码。最后,您需要给要发布的参数指定名称。
例如(请注意,这使用的是dart:io HttpClient,但基本相同):
Future<HttpClientResponse> foo() async { Map<String, dynamic> jsonMap = { 'homeTeam': {'team': 'Team A'}, 'awayTeam': {'team': 'Team B'}, }; String jsonString = json.enpre(jsonMap); // enpre map to json String paramName = 'param'; // give the post param a name String formBody = paramName + '=' + Uri.enpreQueryComponent(jsonString); List<int> bodyBytes = utf8.enpre(formBody); // utf8 enpre 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版本,则需要对Map进行一些调整。正文必须是Map
此代码
Map<String, String> body = { 'name': 'doodle', 'color': 'blue', 'homeTeam': json.enpre( {'team': 'Team A'}, ), 'awayTeam': json.enpre( {'team': 'Team B'}, ), }; Response r = await post( url, body: body, );在电线上产生这个
名称= 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.enpre({ 'homeTeam': {'team': 'Team A'}, 'awayTeam': {'team': 'Team B'}, }), }; Response r = await post( url, body: body, );在电线上产生这个
名称= doodle&color = blue&teamJson
=%7B%22homeTeam%22%3A%7B%22team%22%3A%22Team +
A%22%7D%2C%22awayTeam%22%3A%7B%22team%22%3 %%% Team + B %22%7D%7D
package:http客户端负责:对Uri.enpreQueryComponent进行编码,对utf8进行编码(请注意,这是默认设置,因此无需指定它),并在Content-
Length标头中发送长度。您仍然必须进行json编码。



