Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the String value of an HttpEntity when EntityUtils.toString() returns an exception?

Tags:

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.

like image 498
sangfroid Avatar asked Aug 30 '11 17:08

sangfroid


People also ask

How do you read HttpEntity?

To read the content from the entity, you can either retrieve the input stream via the HttpEntity. getContent() method, which returns an InputStream, or you can supply an output stream to the HttpEntity. writeTo(OutputStream) method, which will return once all content has been written to the given stream.

What does EntityUtils toString do?

EntityUtils. toString(HttpEntity) interprets that content as a String and returns it to you.

How do I get http body response?

To get the response body as a string we can use the EntityUtils. toString() method. This method read the content of an HttpEntity object content and return it as a string. The content will be converted using the character set from the entity object.


1 Answers

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

String responseXml = EntityUtils.toString(httpResponse.getEntity()); EntityUtils.consume(httpResponse.getEntity()); 
like image 93
Ahmad Nadeem Avatar answered Oct 04 '22 18:10

Ahmad Nadeem