Sam*_*Sam 1 flutter flutter-http
嗨,当我通过Postman发出 API 发布请求时,获取正确的状态代码为 200,但使用 flutter/http 包 (v0.12.0+4) 或 DIO (v3.0.9) 包进行相同的 api 调用时,我得到的状态代码为302,但是post成功,数据保存在DB上。我怎样才能为此获得状态 200 或者有更好的方法来处理帖子中的重定向
发现了这些 git hub 问题,但没有关于如何解决这个问题的答案 https://github.com/dart-lang/http/issues/157
https://github.com/dart-lang/sdk/issues/38413
Code making API post
...........
final encoding = Encoding.getByName('utf-8');
final headers = {
HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8',
HttpHeaders.acceptHeader: 'application/json',
};
//String jsonBody = jsonEncode(feedRequest.toJsonData());
String jsonBody = feedRequest.toJsonData();
print('response.SubmitFeedApiRequest>:' + feedRequest.toJsonData());
print('jsonBody:>' + jsonBody);
String url ='https://myapp';
final response = await http.post(url,
headers: headers, body: jsonBody, encoding: encoding);
print('response.statusCode:' + response.statusCode.toString());
if (response.statusCode == 200) {
print('response.data:' + response.body);
} else {
print('send failed');
}
...............
Run Code Online (Sandbox Code Playgroud)
===根据@midhun-mp 评论更新工作代码
final response = await http.post(url,
headers: headers, body: jsonBody, encoding: encoding);
print('response.statusCode:' + response.statusCode.toString());
if (response.statusCode == 302) {
//print('response.headers:' + response.headers.toString());
if (response.headers.containsKey("location")) {
final getResponse = await http.get(response.headers["location"]);
print('getResponse.statusCode:' + getResponse.statusCode.toString());
return SubmitFeedApiResponse(success: getResponse.statusCode == 200);
}
} else {
if (response.statusCode == 200) {
// print('response.data:' + response.body);
return SubmitFeedApiResponse.fromJson(json.decode(response.body));
}
return SubmitFeedApiResponse(success: false);
}
}
Run Code Online (Sandbox Code Playgroud)
302 不是错误,而是重定向状态码。http 包不支持 POST 请求的重定向。
所以你必须手动处理重定向。在您的代码中,您还必须添加状态代码 302 的条件。当状态代码为 302 时,在响应标头中查找重定向 url,并对该 url 执行 http GET。
| 归档时间: |
|
| 查看次数: |
3746 次 |
| 最近记录: |