我正在尝试在内容类型为 url 编码的情况下发出一个 post 请求。当我写 body : json.encode(data)
,它编码为纯文本。
如果我写 body: data
我收到错误 type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' in type cast
这是数据对象
var match = {
"homeTeam": {"team": "Team A"},
"awayTeam": {"team": "Team B"}
};
还有我的要求
var response = await post(Uri.parse(url),
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
body: match,
encoding: Encoding.getByName("utf-8"));
最佳答案
您需要添加三个额外的步骤: 首先,您需要将 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
版本,那么您需要稍微调整一下您的 map 。 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%22Team+B%22%7D%7D
package:http
客户端负责:对 Uri.encodeQueryComponent 进行编码,utf8 编码(注意这是默认值,因此无需指定)并在 Content-Length header 中发送长度。您仍然必须进行 json 编码。
https://stackoverflow.com/questions/49797558/