在Android中获得400 HTTP响应的响应正文?

And*_*ton 0 java android httpclient

我正在与一个我无法更改的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
            }
   }
Run Code Online (Sandbox Code Playgroud)

Buh*_*ndi 6

这样的东西,使用org.apache.http.util.EntityUtils:

HttpRequestBase base = new HttpGet(url);
HttpResponse response = httpClient.execute(base);
String jsonString = EntityUtils.toString(response.getEntity());
Run Code Online (Sandbox Code Playgroud)

PS:这是盲编码,因为我不知道你尝试了什么.

要获取状态代码:

int statusCode = response.getStatusLine().getStatusCode();
Run Code Online (Sandbox Code Playgroud)

要以字节数组获取实体主体:

byte[] data = EntityUtils.toByteArray(response.getEntity());
Run Code Online (Sandbox Code Playgroud)