dart Flutter HTTP Post返回415

wwodge7n  于 2023-07-31  发布在  Flutter
关注(0)|答案(3)|浏览(207)

我在我的flutter应用程序上使用Method.Post dart库时遇到问题。似乎当我试图从我的WebAPI发布数据时,它给了我一个StatusCode 415。下面是我的代码:
密码登录:

Future<User> login(User user) async {
print(URLRequest.URL_LOGIN);
return await _netUtil.post(Uri.encodeFull(URLRequest.URL_LOGIN), body: {
  'username': user.username,
  'password': user.password
}, headers: {
  "Accept": "application/json",
}).then((dynamic res) {
  print(res.toString());
});
}

字符串
代码NetworkUtils:

Future<dynamic> post(String url, {Map headers, body, encoding}) async {
return await http
    .post(url, body: body, headers: headers, encoding: encoding)
    .then((http.Response response) {
  final String res = response.body;
  final int statusCode = response.statusCode;

  if (statusCode < 200 || statusCode > 400 || json == null) {
    throw new Exception('Error while fetching data.');
  }

  return _decoder.convert(res);
});
}


有谁知道我的代码是怎么回事吗?

6za6bjd0

6za6bjd01#

尝试添加此新标头:

headers: {
  "Accept": "application/json",
  "content-type":"application/json"
}

字符串

更新

现在你需要发送JSON数据,像这样:

import 'dart:convert';

         var body = jsonEncode( {
          'username': user.username,
          'password': user.password
        });

        return await _netUtil.post(Uri.encodeFull(URLRequest.URL_LOGIN), body: body, headers: {
          "Accept": "application/json",
          "content-type": "application/json"
        }).then((dynamic res) {
          print(res.toString());
        });
        }

wribegjk

wribegjk2#

@Alvin奎松
我遇到了和你相同的错误,并修复它,请参阅下面。
[错误]
StateError(坏状态:无法设置内容类型为“application/json”的请求的主体字段。)
【理由】
当你使用Flutter插件'http.dart'方法'http.post()'时,你应该详细阅读下面的文档(注意黑色字体):

Sends an HTTP POST request with the given headers and body to the given URL.
[body] sets the body of the request. It can be a [String], a [List<int>] or
a [Map<String, String>]. If it's a String, it's encoded using [encoding] and
used as the body of the request. The content-type of the request will
default to "text/plain".

If [body] is a List, it's used as a list of bytes for the body of the
request.

字符串

如果[body]是一个Map,则使用[encoding]将其编码为表单字段。请求的content-type将设置为"application/x-www-form-urlencoded";这不能被覆盖。

[encoding] defaults to [utf8].

For more fine-grained control over the request, use [Request] or
[StreamedRequest] instead.
Future<Response> post(Uri url,
{Map<String, String>? headers, Object? body, Encoding? encoding}) =>
_withClient((client) =>
    client.post(url, headers: headers, body: body, encoding: encoding));


[解决方案]
所以只要将你的主体编码为字符串,然后你就可以将header 'content-type'设置为'application/json'。请参阅@diegoveloper的代码回答!

bqucvtff

bqucvtff3#

如果你使用Flutter和Rust后端,你可能有几件事要做。它以前在NodeJS上工作得很好,所以我有点惊讶,不得不一点一点地调试。
1/使用jsonEncode而不是toJson()进行编码

String body = jsonEncode(user); // give you a string instead of a Map.

字符串
userClass User的Object,定义如下,当然你可以在请求的正文中使用任何你想要发送的Object。
2/添加标题

var headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    };


现在请求应该可以工作了:

final response = await http.post(Uri.parse(url), headers: headers, body: body);


我还按照@Rooshan的答案让它工作,并使用String而不是Map,但至少可以说它不是很漂亮,但它仍然完成了这项工作:

String toJson() => """{
    "firstname": "$firstname",
    "lastname": "$lastname",
    "email": "$email",
    "password": "$password"
  }""";


在这种情况下,你可以直接写:

String body = user.toJson();


对于参考类用户:

class User {
  String firstname;
  String lastname;
  String email;
  String? password;

User(this.firstname, this.lastname, this.email, {this.password = ""});

  Map<String, dynamic> toJson() => {
        "firstname": firstname,
        "lastname": lastname,
        "email": email,
        "password": password!,
      };
}

相关问题