[英]flutter: Content-type must be application/json
我对http发布请求有疑问。 我收到响应“内容类型必须为application / json”,但是我正在设置标题以指定内容为json类型。
const Map<String, String> header = {
'Content-type': 'application/json',
'Accept': 'application/json',
};
static void init() async {
var body =
{
"username": username, // String username defined above
"password": password, // String password defined above
};
var response = await http.post(url, body: json.encode(body), headers: header);
print(response.body);
}
如上所述,我期望它能够正常工作并返回有效的json响应,但是我收到的错误代码为400,并显示消息“ Content-type must be application / json”。 我不太确定如何解决此问题,我曾使用过这种方法来传递http.Post请求,而在其他时间,它一直都有效。
对于所有想知道的人,Richard Heap在上面的评论中是正确的,直到基本的HttpClient都解决了这个问题。 (我不确定如何将答案归功于他,如果有人知道请告知,以便我可以这样做)。
以下是用于使我的代码用于文档目的的代码段
static void init() async {
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set('Content-type', 'application/json');
request.add(utf8.encode(json.encode(rawBody)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
var jsonReply = json.decode(reply);
httpClient.close();
}
这给了我所需的响应,非常感谢Richard,我从来没有想过要成为一个扑朔迷离的新用户。
1号 如果您使用的是http.post ,则无需重新指定application / json标头。 您可以尝试删除headers:header吗?
2个 请仔细检查正文是否为json格式。
使用http.post的简单示例
const Map<String, String> header = {
'Content-type': 'application/json',
'Accept': 'application/json',
};
var res = await http.post(
'https://jsonplaceholder.typicode.com/posts',
body: {'title': 'foo', 'body': 'bar', 'userId': '222110011'});
print(res.body);
看到我没有发送http标头。
希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.