我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)
有谁知道我的代码发生了什么?
尝试添加以下新标题:
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)
| 归档时间: |
|
| 查看次数: |
1551 次 |
| 最近记录: |