在 Android 中获取 400 HTTP 响应的响应正文?
我正在与一个无法更改的 API 进行通信,当 API 端未验证请求时,该 API 会发送 400 响应。这是一个有效的 HTTP 请求,但请求数据未通过应用程序的验证规则。
400 响应包含一个 JSON 负载,其中包含有关请求未通过验证的原因的信息。
我似乎无法获取响应正文,因为抛出了 HttpRequestException。有人知道如何检索这个响应正文吗?
try {
HttpUriRequest request = params[0];
HttpResponse serverResponse = mClient.execute(request);
BasicResponseHandler handler = new BasicResponseHandler();
String response = handler.handleResponse(serverResponse);
return response;
} catch(HttpResponseException e) {
// Threw HttpError
Log.d(TAG, "HttpResponseException : " + e.getMessage());
Log.d(TAG, "Status Code : " + e.getStatusCode());
// TODO API returns 400 on successful HTTP payload, but invalid user data
if(e.getStatusCode() == 400) {
// Information on API error inside Response body
}
}
I'm communicating with an API that I can not change that sends a 400 response when a request is not validated on the API side. It is a valid HTTP request, but the request data does not pass the application's validation rules.
The 400 response contains a JSON payload that has information on why the request did not pass validation.
I can't seem to get the response body because an HttpRequestException is thrown. Does anybody know how to retrieve this response body?
try {
HttpUriRequest request = params[0];
HttpResponse serverResponse = mClient.execute(request);
BasicResponseHandler handler = new BasicResponseHandler();
String response = handler.handleResponse(serverResponse);
return response;
} catch(HttpResponseException e) {
// Threw HttpError
Log.d(TAG, "HttpResponseException : " + e.getMessage());
Log.d(TAG, "Status Code : " + e.getStatusCode());
// TODO API returns 400 on successful HTTP payload, but invalid user data
if(e.getStatusCode() == 400) {
// Information on API error inside Response body
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
像这样,使用
org.apache.http.util.EntityUtils
:PS:这是盲目编码,因为我不知道你尝试过什么。
获取状态码:
获取字节数组中的实体主体:
Something like this, using
org.apache.http.util.EntityUtils
:PS: This is blind coding as I don't know what you tried yet.
To get status code:
To get the entity body in byte array:
尝试这样:
Try that way:
这就是我以
byte[]
形式发送和获取 Http 响应的方式。当然,如果需要,您可以将其更改为字符串。希望有帮助!
This is how I send and get Http response as an
byte[]
.Of course you can change it to string if you want.Hope it helps!