Server API 不接受 JSON 编码数据 Flutter

huangapple go评论51阅读模式
英文:

Server API not accept JSON edcoded data Flutter

问题

Edit:
经过几个小时的工作,可能是因为当我发送"content-type": "application/json"时,它发送"application/json; charset=utf-8"到服务器。如何从标头中删除 ; charset=utf-8

Edit2:
问题是因为Flutter在Content-type中发送了charset=utf-8。我通过联系我的后端开发人员允许在Content-type标头中使用"application/json; charset=utf-8"来修复了。

我向服务器发送POST请求,返回错误

{ "error": "true", "code": "30", "message": "数据必须是JSON" }

这是我的代码:

Future<void> _getToken() async {
  final url = Uri.parse("http://apimobile.xxxx.co.id/Apimobile/auth");
  final Map<String, String> data = {
    "username": "xxxx",
    "password": "xxxx"
  };
  try {
    final response = await http.post(url,
        headers: {
          "Content-Type": "application/json",
          "accept": "application/json",
        },
        body: jsonEncode(data));
    print(response.body);
    final responseData = jsonDecode(response.body);
    _token = responseData["message"];
  } catch (error) {
    throw error;
  }
}

我的代码有什么问题吗? 🤔

这个API在Postman、ThunderClient、VS Code和React Native中工作正常

Server API 不接受 JSON 编码数据 Flutter

感谢您的帮助

英文:

Edit:
After hours of work, i might because when i send "content-type": "application/json", it send "application/json; charset=utf-8" to server. How to remove ; charset=utf-8 from header?

Edit2:
The problem is because flutter send charset=utf-8 in Content-type. I fix by contact my backend developer to allow "application/json; charset=utf-8" in Content-type header

I send post request to server, return error

{&quot;error&quot;:&quot;true&quot;,&quot;code&quot;:&quot;30&quot;,&quot;message&quot;:&quot; Data must JSON&quot;}

This is my code:

Future&lt;void&gt; _getToken() async {
final url =
    Uri.parse(&quot;http://apimobile.xxxx.co.id/Apimobile/auth&quot;);
final Map&lt;String, String&gt; data = {
  &quot;username&quot;: &quot;xxxx&quot;,
  &quot;password&quot;: &quot;xxxx&quot;
};
try {
  final response = await http.post(url,
      headers: {
        &quot;Content-Type&quot;: &quot;application/json&quot;,
        &quot;accept&quot;: &quot;application/json&quot;,
      },
      body: jsonEncode(data));
  print(response.body);
  final responseData = jsonDecode(response.body);
  _token = responseData[&quot;message&quot;];
} catch (error) {
  throw error;
 }
}

Is there something wrong in my code? 🤔

The API work on Postman, ThunderClient VS Code, and React Native

Server API 不接受 JSON 编码数据 Flutter

Thanks for your help

答案1

得分: 1

创建一个类似这样的模型:

import 'dart:convert';

LoginData loginDataFromJson(String str) => LoginData.fromJson(json.decode(str));

String loginDataToJson(LoginData data) => json.encode(data.toJson());

class LoginData {
  LoginData({
    required this.username,
    required this.password,
  });

  final String username;
  final String password;

  factory LoginData.fromJson(Map<String, dynamic> json) => LoginData(
        username: json["username"],
        password: json["password"],
      );

  Map<String, dynamic> toJson() => {
        "username": username,
        "password": password,
      };

  @override
  String toString() {
    return '$runtimeType($username, $password)';
  }

  @override
  bool operator ==(Object other) {
    if (other is LoginData) {
      return username == other.username && password == other.username;
    }
    return false;
  }

  @override
  int get hashCode => hash2(username, password);
}

现在你可以像这样编写你的代码:

Future<void> _getToken() async {
final url =
    Uri.parse("http://apimobile.xxxx.co.id/Apimobile/auth");
final LoginData data = LoginData(
  username: "xxxx",
  password: "xxxx"
);
try {
  final response = await http.post(url,
      headers: {
        "Content-Type": "application/json",
        "accept": "application/json",
      },
      body: data.toJson());
  print(response.body);
  final responseData = jsonDecode(response.body);
  _token = responseData["message"];
} catch (error) {
  throw error;
 }
}
英文:

Create model like this:

import &#39;dart:convert&#39;;

LoginData loginDataFromJson(String str) =&gt; LoginData.fromJson(json.decode(str));

String loginDataToJson(LoginData data) =&gt; json.encode(data.toJson());

class LoginData {
  LoginData({
    required this.username,
    required this.password,
  });

  final String username;
  final String password;

  factory LoginData.fromJson(Map&lt;String, dynamic&gt; json) =&gt; LoginData(
        username: json[&quot;username&quot;],
        password: json[&quot;password&quot;],
      );

  Map&lt;String, dynamic&gt; toJson() =&gt; {
        &quot;username&quot;: username,
        &quot;password&quot;: password,
      };

  @override
  String toString() {
    return &#39;$runtimeType($username, $password)&#39;;
  }

  @override
  bool operator ==(Object other) {
    if (other is LoginData) {
      return username == other.username &amp;&amp; password == other.username;
    }
    return false;
  }

  @override
  int get hashCode =&gt; hash2(username, password);
}

And now you can write your code like this:

Future&lt;void&gt; _getToken() async {
final url =
    Uri.parse(&quot;http://apimobile.xxxx.co.id/Apimobile/auth&quot;);
final LoginData data = LoginData(
  username: &quot;xxxx&quot;,
  password: &quot;xxxx&quot;
);
try {
  final response = await http.post(url,
      headers: {
        &quot;Content-Type&quot;: &quot;application/json&quot;,
        &quot;accept&quot;: &quot;application/json&quot;,
      },
      body: data.toJson());
  print(response.body);
  final responseData = jsonDecode(response.body);
  _token = responseData[&quot;message&quot;];
} catch (error) {
  throw error;
 }
}

答案2

得分: 0

http.post 方法中的 headers 字段需要更改,使其具有 Content-Type 等于 application/jsonaccept 等于 application/json

Future<void> _getToken() async {
  final url = Uri.parse("http://apimobile.xxxx.co.id/Apimobile/auth");
  final Map<String, String> data = {
    "username": "xxxx",
    "password": "xxxx"
  };
  try {
    final response = await http.post(url,
        headers: {
          "Content-Type": "application/json",
          "accept": "application/json",
        },
        body: jsonEncode(data));
    print(response.body);
    final responseData = jsonDecode(response.body);
    _token = responseData["message"];
  } catch (error) {
    throw error;
  }
}
英文:

The headers field in the http.post method has to be changed to have Content-Type equal to application/json and accept equal to application/json.

Future&lt;void&gt; _getToken() async {
final url =
    Uri.parse(&quot;http://apimobile.xxxx.co.id/Apimobile/auth&quot;);
final Map&lt;String, String&gt; data = {
  &quot;username&quot;: &quot;xxxx&quot;,
  &quot;password&quot;: &quot;xxxx&quot;
};
try {
  final response = await http.post(url,
      headers: {
        &quot;Content-Type&quot;: &quot;application/json&quot;,
        &quot;accept&quot;: &quot;application/json&quot;,
      },
      body: jsonEncode(data));
  print(response.body);
  final responseData = jsonDecode(response.body);
  _token = responseData[&quot;message&quot;];
} catch (error) {
  throw error;
 }
}

答案3

得分: 0

尝试使用 convert 来编码您的数据:

import 'dart:convert' as convert;

//...

const JsonEncoder encoder = JsonEncoder();
final response = await http.post(url,
    headers: {
        "Content-Type": "application/json",
        "accept": "application/json",
    },
    body: encoder.convert(data)
);
    
希望这能帮助您。


<details>
<summary>英文:</summary>

Try encode your data using convert

    import &#39;dart:convert&#39; as convert;

    //...

    const JsonEncoder encoder = JsonEncoder();
    final response = await http.post(url,
        headers: {
            &quot;Content-Type&quot;: &quot;application/json&quot;,
            &quot;accept&quot;: &quot;application/json&quot;,
        },
        body: encoder.convert(data)
    );
    
Hope this will help


</details>



huangapple
  • 本文由 发表于 2023年2月6日 13:05:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75357499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定