开发者

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

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 {

    Htt开发者_如何学CpClient 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());


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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜