我在我的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);
});
}
型
有谁知道我的代码是怎么回事吗?
3条答案
按热度按时间6za6bjd01#
尝试添加此新标头:
字符串
更新
现在你需要发送JSON数据,像这样:
型
wribegjk2#
@Alvin奎松
我遇到了和你相同的错误,并修复它,请参阅下面。
[错误]
StateError(坏状态:无法设置内容类型为“application/json”的请求的主体字段。)
【理由】
当你使用Flutter插件'http.dart'方法'http.post()'时,你应该详细阅读下面的文档(注意黑色字体):
字符串
如果[body]是一个Map,则使用[encoding]将其编码为表单字段。请求的content-type将设置为
"application/x-www-form-urlencoded"
;这不能被覆盖。型
[解决方案]
所以只要将你的主体编码为字符串,然后你就可以将header 'content-type'设置为'application/json'。请参阅@diegoveloper的代码回答!
bqucvtff3#
如果你使用Flutter和Rust后端,你可能有几件事要做。它以前在NodeJS上工作得很好,所以我有点惊讶,不得不一点一点地调试。
1/使用
jsonEncode
而不是toJson()进行编码字符串
user
是Class User
的Object,定义如下,当然你可以在请求的正文中使用任何你想要发送的Object。2/添加标题
型
现在请求应该可以工作了:
型
我还按照@Rooshan的答案让它工作,并使用String而不是Map,但至少可以说它不是很漂亮,但它仍然完成了这项工作:
型
在这种情况下,你可以直接写:
型
对于参考类用户:
型