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.
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.
EntityUtils. toString(HttpEntity) interprets that content as a String and returns it to you.
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.
Appache has already provided a Util class for that called EntityUtils.
String responseXml = EntityUtils.toString(httpResponse.getEntity()); EntityUtils.consume(httpResponse.getEntity());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With