我在使用Method.Post
飞镖库的flutter应用程序中使用http
时遇到问题。看来,当我尝试从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);
});
}
有人知道我的代码怎么了吗?
答案 0 :(得分:3)
尝试添加此新标题:
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());
});
}
答案 1 :(得分:0)
@阿尔文奎松
我遇到了与您相同的错误并已修复,请参见下文。
[错误]
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.
"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));
[解决方案]
所以只需将您的正文编码为字符串,然后您就可以将标题“内容类型”设置为“应用程序/json”。 看到@diegoveloper 的代码回答了!