【问题标题】:Unhandled Exception: Bad state: Cannot set the body fields of a Request with content-type "application/json"未处理的异常:错误状态:无法设置内容类型为“application/json”的请求的正文字段
【发布时间】:2020-04-05 21:39:39
【问题描述】:

我正在尝试从 API 获取数据。我需要从 body 传递值,当我在 flutter 中运行下面的代码时显示上面的错误消息

  signIn(String username,String password) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var jsonResponse = null;
 var response = await http.post("http://10.0.2.2:5554/api/login/login",
        headers : {
          "Content-type": "application/json",
          "Accept": "application/json",
          "charset":"utf-8"
        },
     body:{
       "username": '$username' ,
       "password":  '$password'
     });

【问题讨论】:

  • 你是在问如何在 Postman 中做到这一点?
  • 不抱歉,我编辑问题。

标签: flutter dart


【解决方案1】:

你传递的body值是一个map。

要使其正常工作,您可以将标题的 Content-Type 更改为:"application/x-www-form-urlencoded"

将地图编码为字符串并将其传递给正文:

body: json.encode({"username": '$username', "password": '$password'});

后一种选择不要忘记import 'dart:convert';

【讨论】:

    猜你喜欢
    • 2019-07-17
    • 2020-08-10
    • 2023-01-11
    • 2015-05-29
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    相关资源
    最近更新 更多