Flutter HTTP Post返回415

Alv*_*zon 3 dart flutter

Method.Post在使用httpdart库的flutter应用程序中使用时遇到问题。看来,当我尝试从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());
});
}
Run Code Online (Sandbox Code Playgroud)

代码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);
});
}
Run Code Online (Sandbox Code Playgroud)

有谁知道我的代码发生了什么?

die*_*per 6

尝试添加以下新标题:

headers: {
  "Accept": "application/json",
  "content-type", "application/json"
}
Run Code Online (Sandbox Code Playgroud)

更新

好的,现在您需要发送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());
        });
        }
Run Code Online (Sandbox Code Playgroud)

  • 尝试了您的建议,但出现错误:`错误状态:无法设置内容类型为“application/json”的请求的正文字段。`现在发生了什么?抱歉,新来的颤振。 (2认同)