27

I keep running into this situation where I get back a bad HTTP response (like a 400) but cannot look at the HttpEntity in the HttpResponse object. When I step through with the debugger, I can see that the entity has content (length > 0) and I can even look at the content, but all I see is an array of numbers (ASCII codes I guess?) which isn't helpful. I'll call EntityUtils.toString() on the entity, but I get back an exception -- either an IOException, or some kind of "object is in an invalid state" exception. This is really frustrating! Is there any way to get at this content in a human-readable form?

Here is my code :

    protected JSONObject makeRequest(HttpRequestBase request) throws ClientProtocolException, IOException, JSONException, WebRequestBadStatusException {

    HttpClient httpclient = new DefaultHttpClient();

    try {
        request.addHeader("Content-Type", "application/json");
        request.addHeader("Authorization", "OAuth " + accessToken);
        request.addHeader("X-PrettyPrint", "1");

        HttpResponse response = httpclient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode < 200 || statusCode >= 300) {
            throw new WebRequestBadStatusException(statusCode);
        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            return new JSONObject(EntityUtils.toString(entity));
        } else {
            return null;
        }

    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

See where I throw the exception? What I'd like to do is suck out the content of the HttpEntity and put it in the exception.

skaffman
  • 398,947
  • 96
  • 818
  • 769
sangfroid
  • 3,733
  • 11
  • 38
  • 42
  • 1
    If stringizing fails, you could always get the raw bytes with `EntityUtils.toByteArray()` and produce a hex dump of those bytes yourself. – hmakholm left over Monica Aug 30 '11 at 18:17
  • Yeah, I thought of that. Know of any utilities that'll take the [100, 21, 45, 22] type of output we get from the debugger and turn that into something human-readable? – sangfroid Aug 30 '11 at 19:08
  • 1
    Try the String constructor: http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html#String(byte[], java.lang.String) – Lauri Piispanen Sep 01 '11 at 10:17

4 Answers4

47

Appache has already provided a Util class for that called EntityUtils.

String responseXml = EntityUtils.toString(httpResponse.getEntity());
EntityUtils.consume(httpResponse.getEntity());
Ahmad Nadeem
  • 2,056
  • 1
  • 18
  • 19
22

Here's some code to view the entity as a string (given that your request contentType is html or similar):

   String inputLine ;
 BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
 try {
       while ((inputLine = br.readLine()) != null) {
              System.out.println(inputLine);
       }
       br.close();
  } catch (IOException e) {
       e.printStackTrace();
  }
JaVaBoy
  • 419
  • 1
  • 4
  • 9
6

To enable a human readable form you can convert HttpEntity to string with UTF-8 code

EntityUtils.toString(response.getEntity(), "UTF-8")

This will give you Response parameters in json form like:

{ "error": { "errors": [ { "domain": "global", "reason": "forbidden", "message": "Forbidden" } ], "code": 403, "message": "Forbidden" }}

Hope this solves the issue.

Anand Tuli
  • 179
  • 2
  • 3
1

In general if you want to convert your DTO to String format then you can use ObjectMapper. Please find the following example if it helpful.

public static String getObjectAsString(Object object) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.writeValueAsString(object);
    } catch (Exception e) {
        return null;
    }
}
Sumanth Varada
  • 1,122
  • 1
  • 16
  • 17