嗨,当我通过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');
}
...............
===根据@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);
}
}