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

play httpentity to string
string to httpentity
how to get json object from http response in java
java lang illegalargumentexception entity may not be null
convert httpresponse to java object
get data from http response
how to convert response to string
httpclient get response body

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.


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

String responseXml = EntityUtils.toString(httpResponse.getEntity());
EntityUtils.consume(httpResponse.getEntity());

Java Code Examples org.apache.http.util.EntityUtils.toString, toString(httpEntity); EntityUtils.consume(httpEntity); } catch (IOException e) { e. toString().equals("result")) return new BigInteger(a.get(j). public String getAsString(String url) throws Exception { HttpGet get = new HttpGet(url); map of headers and their corresponding values * @param postData * request body data in byte  static String: toString(HttpEntity entity, String defaultCharset) Get the entity content as a String, using the provided default character set if none is found in the entity. static void: updateEntity(HttpResponse response, HttpEntity entity) Updates an entity in a response by first consuming an existing entity, then setting the new one.


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

Java Code Examples org.apache.http.util.EntityUtils, toString(httpEntity); }catch(IOException e){ logger.error("Exception occurred while reading HTTP response closeableHttpResponse = closeableHttpClient.​execute(httpUriRequest); String response = EntityUtils. private byte[] bytes(​HttpEntity entity){ try { return EntityUtils. Get(url); HttpEntity resEntity = request.​execute(). String json_string = EntityUtils.toString(response.getEntity()); JSONObject temp1 = new JSONObject(json_string); The above code will throw an exception and it looks like the JSON array brackets are to blame. But it’s fine to have a JSON array as the top level element! You just need to use JSONArray() instead of JSONObject:


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.

org.apache.http.util.EntityUtils.toString java code examples, Best Java code snippets using org.apache.http.util. getStatusCode() == 200) { return; } StatusLine status = response. getEntity()); } catch (IOException e) { String errMsg = "Unable to get or parse HTTP response for " + toString(entity)); } EntityUtils.consume(entity); ret = true; } catch (Exception e) { LOG.error("​Exception  The following are top voted examples for showing how to use org.apache.http.HttpEntity.These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.


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;
    }
}

org.apache.http.HttpResponse.getEntity java code examples, public InputStream getInputStream() throws IOException { return response Best Java code snippets using org.apache.http. Common ways to obtain HttpResponse post() throws Exception{ HttpClient client = new DefaultHttpClient(); HttpPost HttpResponse response = client.execute(post); String result = EntityUtils. Obtains the message entity of this response, if any. The entity is provided by calling #setEntity.


EntityUtils (Apache HttpCore 4.4.13 API), Read the contents of an entity and return it as a String. static String · toString(​HttpEntity entity, Charset defaultCharset) Get the entity content as a String, using the  The following are top voted examples for showing how to use org.apache.http.util.EntityUtils.These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.


How do I get HTTP response body as a string?, 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. HttpClient client = HttpClientBuilder.create().build(); HttpGet request toString(entity); System.out.println(content); } catch (IOException e)  Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.


Java Code Examples of org.apache.http.util.EntityUtils, getEntity(); if (httpEntity != null) { return EntityUtils. toString(entity); return processResponse(stringResponse,quoteAttributes); } } catch getStatusCode(),​responseClass); } catch ( Exception e) { throw new if (!matcher.find()) throw new BankException("Couldn't parse value! If there was an error, it parses the error codes. The following are top voted examples for showing how to use org.apache.http.entity.StringEntity.These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.