1

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
            }
   }
Andy Lawton
  • 295
  • 4
  • 8

4 Answers4

7

Something like this, using org.apache.http.util.EntityUtils:

HttpRequestBase base = new HttpGet(url);
HttpResponse response = httpClient.execute(base);
String jsonString = EntityUtils.toString(response.getEntity());

PS: This is blind coding as I don't know what you tried yet.

To get status code:

int statusCode = response.getStatusLine().getStatusCode();

To get the entity body in byte array:

byte[] data = EntityUtils.toByteArray(response.getEntity());
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
  • Thanks! BasicResponseHandler was throwing the HttpException error...EntityUtils lets me get the response body regardless of HTTP status code. – Andy Lawton Oct 12 '11 at 06:29
2

Try that way:

if (this.responseCode == HttpURLConnection.HTTP_OK) {
 inputStream = httpUrlConnection.getInputStream();
} else {
inputStream = httpUrlConnection.getErrorStream();
}
1

This is how I send and get Http response as an byte[].Of course you can change it to string if you want.

                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();

Hope it helps!

Android-Droid
  • 14,365
  • 41
  • 114
  • 185
  • 1
    Excellent! Thanks for also providing how to get the HTTP status code. Cheers – Andy Lawton Oct 12 '11 at 06:31
  • @Andy Lawton, I don't get it, you could just do `byte[] data = EntityUtils.toByteArray(response.getEntity());`! See my updated post. – Buhake Sindi Oct 12 '11 at 06:51
  • @Android-Droid, `EntityUtils.toString(response.getEntity()).getBytes();` is not an effective way of getting byte arrays since you're "assuming" there is the encoding is standard for all data. Rather use, `EntityUtils.toByteArray()` instead. – Buhake Sindi May 29 '13 at 07:00
0
                     if (serverResponseCode == 200) {

                     InputStream in = new BufferedInputStream(conn.getInputStream());
                     BufferedReader r = new BufferedReader(new InputStreamReader(in));
                     StringBuilder total = new StringBuilder();
                     for (String line; (line = r.readLine()) != null; ) {
                         total.append(line).append('\n');
                     }
                     Log.e("temp", String.valueOf(total));

                 }
                 else {
                     InputStream in = new BufferedInputStream(conn.getErrorStream());
                     BufferedReader r = new BufferedReader(new InputStreamReader(in));
                     StringBuilder total = new StringBuilder();
                     for (String line; (line = r.readLine()) != null; ) {
                         total.append(line).append('\n');
                     }
                     Log.e("temp", String.valueOf(total));

                 }
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 20 '22 at 05:51