当 EntityUtils.toString() 返回异常时,有没有办法获取 HttpEntity 的 String 值? [英] Is there a way to get the String value of an HttpEntity when EntityUtils.toString() returns an exception?

查看:43
本文介绍了当 EntityUtils.toString() 返回异常时,有没有办法获取 HttpEntity 的 String 值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直遇到这种情况,我得到一个错误的 HTTP 响应(如 400),但无法查看 HttpResponse 对象中的 HttpEntity.当我逐步调试调试器时,我可以看到实体有内容(长度 > 0),我什至可以查看内容,但我看到的只是一个数字数组(我猜是 ASCII 代码?)有帮助.我将在实体上调用 EntityUtils.toString(),但我得到一个异常——IOException 或某种对象处于无效状态"异常.这真是令人沮丧!有没有办法以人类可读的形式获取这些内容?

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?

这是我的代码:

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

看到我在哪里抛出异常了吗?我想要做的是吸出HttpEntity的内容并将其放入异常中.

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 已经提供了一个名为 EntityUtils.

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

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

这篇关于当 EntityUtils.toString() 返回异常时,有没有办法获取 HttpEntity 的 String 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆