颤抖:内容类型必须为application / json [英] flutter: Content-type must be application/json

查看:174
本文介绍了颤抖:内容类型必须为application / json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对http发布请求有疑问。我得到响应内容类型必须是application / json,但是我设置了标题以指定内容为json类型。

I'm having issues with an http post request. I get the response 'Content-type must be application/json', however I am setting the header to specify the content is of type 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,并显示消息内容类型必须为application / json。我不太确定如何解决此问题,我曾使用过这种方法来传递http.Post请求,而在其他时间,它一直有效。

As mentioned above, I'm expecting this to work and return a valid json response, however I am receiving an error code of 400, with the message 'Content-type must be application/json'. I'm not quite sure how to fix this, I have used this method to deliver http.Post requests various other times and it has always worked.

推荐答案

对于所有想知道的人,上面注释中的Richard Heap是正确的,直到基本的HttpClient都解决了这个问题。 (我不确定如何将答案归功于他,如果有人知道请告知,以便我可以这样做。)。

For all those wondering, Richard Heap in the comment above was right, going down to the base HttpClient resolved this issue. (I'm not sure how to credit him with the answer, if someone knows please advise so I can do so).

下面是我用来获取的代码段我的代码出于文档目的工作

Below is the code snippet I used to get my code working for documentation purposes

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,我从来没有会认为这是一个扑朔迷离的新用户。

This gave me the response that I needed, thanks a lot Richard, I never would've figured that out as a new user to flutter.

这篇关于颤抖:内容类型必须为application / json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆