Server API 不接受 JSON 编码数据 Flutter

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

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" }

这是我的代码:

  1. Future<void> _getToken() async {
  2. final url = Uri.parse("http://apimobile.xxxx.co.id/Apimobile/auth");
  3. final Map<String, String> data = {
  4. "username": "xxxx",
  5. "password": "xxxx"
  6. };
  7. try {
  8. final response = await http.post(url,
  9. headers: {
  10. "Content-Type": "application/json",
  11. "accept": "application/json",
  12. },
  13. body: jsonEncode(data));
  14. print(response.body);
  15. final responseData = jsonDecode(response.body);
  16. _token = responseData["message"];
  17. } catch (error) {
  18. throw error;
  19. }
  20. }

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

这个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

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

This is my code:

  1. Future&lt;void&gt; _getToken() async {
  2. final url =
  3. Uri.parse(&quot;http://apimobile.xxxx.co.id/Apimobile/auth&quot;);
  4. final Map&lt;String, String&gt; data = {
  5. &quot;username&quot;: &quot;xxxx&quot;,
  6. &quot;password&quot;: &quot;xxxx&quot;
  7. };
  8. try {
  9. final response = await http.post(url,
  10. headers: {
  11. &quot;Content-Type&quot;: &quot;application/json&quot;,
  12. &quot;accept&quot;: &quot;application/json&quot;,
  13. },
  14. body: jsonEncode(data));
  15. print(response.body);
  16. final responseData = jsonDecode(response.body);
  17. _token = responseData[&quot;message&quot;];
  18. } catch (error) {
  19. throw error;
  20. }
  21. }

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

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

  1. import 'dart:convert';
  2. LoginData loginDataFromJson(String str) => LoginData.fromJson(json.decode(str));
  3. String loginDataToJson(LoginData data) => json.encode(data.toJson());
  4. class LoginData {
  5. LoginData({
  6. required this.username,
  7. required this.password,
  8. });
  9. final String username;
  10. final String password;
  11. factory LoginData.fromJson(Map<String, dynamic> json) => LoginData(
  12. username: json["username"],
  13. password: json["password"],
  14. );
  15. Map<String, dynamic> toJson() => {
  16. "username": username,
  17. "password": password,
  18. };
  19. @override
  20. String toString() {
  21. return '$runtimeType($username, $password)';
  22. }
  23. @override
  24. bool operator ==(Object other) {
  25. if (other is LoginData) {
  26. return username == other.username && password == other.username;
  27. }
  28. return false;
  29. }
  30. @override
  31. int get hashCode => hash2(username, password);
  32. }

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

  1. Future<void> _getToken() async {
  2. final url =
  3. Uri.parse("http://apimobile.xxxx.co.id/Apimobile/auth");
  4. final LoginData data = LoginData(
  5. username: "xxxx",
  6. password: "xxxx"
  7. );
  8. try {
  9. final response = await http.post(url,
  10. headers: {
  11. "Content-Type": "application/json",
  12. "accept": "application/json",
  13. },
  14. body: data.toJson());
  15. print(response.body);
  16. final responseData = jsonDecode(response.body);
  17. _token = responseData["message"];
  18. } catch (error) {
  19. throw error;
  20. }
  21. }
英文:

Create model like this:

  1. import &#39;dart:convert&#39;;
  2. LoginData loginDataFromJson(String str) =&gt; LoginData.fromJson(json.decode(str));
  3. String loginDataToJson(LoginData data) =&gt; json.encode(data.toJson());
  4. class LoginData {
  5. LoginData({
  6. required this.username,
  7. required this.password,
  8. });
  9. final String username;
  10. final String password;
  11. factory LoginData.fromJson(Map&lt;String, dynamic&gt; json) =&gt; LoginData(
  12. username: json[&quot;username&quot;],
  13. password: json[&quot;password&quot;],
  14. );
  15. Map&lt;String, dynamic&gt; toJson() =&gt; {
  16. &quot;username&quot;: username,
  17. &quot;password&quot;: password,
  18. };
  19. @override
  20. String toString() {
  21. return &#39;$runtimeType($username, $password)&#39;;
  22. }
  23. @override
  24. bool operator ==(Object other) {
  25. if (other is LoginData) {
  26. return username == other.username &amp;&amp; password == other.username;
  27. }
  28. return false;
  29. }
  30. @override
  31. int get hashCode =&gt; hash2(username, password);
  32. }

And now you can write your code like this:

  1. Future&lt;void&gt; _getToken() async {
  2. final url =
  3. Uri.parse(&quot;http://apimobile.xxxx.co.id/Apimobile/auth&quot;);
  4. final LoginData data = LoginData(
  5. username: &quot;xxxx&quot;,
  6. password: &quot;xxxx&quot;
  7. );
  8. try {
  9. final response = await http.post(url,
  10. headers: {
  11. &quot;Content-Type&quot;: &quot;application/json&quot;,
  12. &quot;accept&quot;: &quot;application/json&quot;,
  13. },
  14. body: data.toJson());
  15. print(response.body);
  16. final responseData = jsonDecode(response.body);
  17. _token = responseData[&quot;message&quot;];
  18. } catch (error) {
  19. throw error;
  20. }
  21. }

答案2

得分: 0

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

  1. Future<void> _getToken() async {
  2. final url = Uri.parse("http://apimobile.xxxx.co.id/Apimobile/auth");
  3. final Map<String, String> data = {
  4. "username": "xxxx",
  5. "password": "xxxx"
  6. };
  7. try {
  8. final response = await http.post(url,
  9. headers: {
  10. "Content-Type": "application/json",
  11. "accept": "application/json",
  12. },
  13. body: jsonEncode(data));
  14. print(response.body);
  15. final responseData = jsonDecode(response.body);
  16. _token = responseData["message"];
  17. } catch (error) {
  18. throw error;
  19. }
  20. }
英文:

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.

  1. Future&lt;void&gt; _getToken() async {
  2. final url =
  3. Uri.parse(&quot;http://apimobile.xxxx.co.id/Apimobile/auth&quot;);
  4. final Map&lt;String, String&gt; data = {
  5. &quot;username&quot;: &quot;xxxx&quot;,
  6. &quot;password&quot;: &quot;xxxx&quot;
  7. };
  8. try {
  9. final response = await http.post(url,
  10. headers: {
  11. &quot;Content-Type&quot;: &quot;application/json&quot;,
  12. &quot;accept&quot;: &quot;application/json&quot;,
  13. },
  14. body: jsonEncode(data));
  15. print(response.body);
  16. final responseData = jsonDecode(response.body);
  17. _token = responseData[&quot;message&quot;];
  18. } catch (error) {
  19. throw error;
  20. }
  21. }

答案3

得分: 0

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

  1. import 'dart:convert' as convert;
  2. //...
  3. const JsonEncoder encoder = JsonEncoder();
  4. final response = await http.post(url,
  5. headers: {
  6. "Content-Type": "application/json",
  7. "accept": "application/json",
  8. },
  9. body: encoder.convert(data)
  10. );
  11. 希望这能帮助您。
  12. <details>
  13. <summary>英文:</summary>
  14. Try encode your data using convert
  15. import &#39;dart:convert&#39; as convert;
  16. //...
  17. const JsonEncoder encoder = JsonEncoder();
  18. final response = await http.post(url,
  19. headers: {
  20. &quot;Content-Type&quot;: &quot;application/json&quot;,
  21. &quot;accept&quot;: &quot;application/json&quot;,
  22. },
  23. body: encoder.convert(data)
  24. );
  25. Hope this will help
  26. </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:

确定