我正在与一个我无法更改的API进行通信,当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
}
}
答案 0 :(得分:6)
这样的事情,使用org.apache.http.util.EntityUtils
:
HttpRequestBase base = new HttpGet(url);
HttpResponse response = httpClient.execute(base);
String jsonString = EntityUtils.toString(response.getEntity());
PS:这是盲编码,因为我不知道你尝试了什么。
获取状态代码:
int statusCode = response.getStatusLine().getStatusCode();
以字节数组获取实体主体:
byte[] data = EntityUtils.toByteArray(response.getEntity());
答案 1 :(得分:2)
尝试这种方式:
if (this.responseCode == HttpURLConnection.HTTP_OK) {
inputStream = httpUrlConnection.getInputStream();
} else {
inputStream = httpUrlConnection.getErrorStream();
}
答案 2 :(得分:0)
这是我发送和获取Http响应的方式byte[]
。当然,如果你愿意,可以将它改为字符串。
byte[] buffer = new byte[1024];
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.rpc.booom.com");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("debug_data","1"));
postParameters.add(new BasicNameValuePair("client_api_ver", "1.0.0.0"));
postParameters.add(new BasicNameValuePair("device_identificator", deviceId));
postParameters.add(new BasicNameValuePair("device_resolution", resolution));
postParameters.add(new BasicNameValuePair("username_hash", hashUser(username,password)));
postParameters.add(new BasicNameValuePair("password_hash", hashPass(username,password)));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.getStatusLine().toString());
buffer = EntityUtils.toString(response.getEntity()).getBytes();
希望它有所帮助!