有没有办法在EntityUtils.toString()返回异常时获取HttpEntity的String值?

问题描述 投票:0回答:4

我不断遇到这种情况,我收到错误的 HTTP 响应(如 400),但无法查看 HttpResponse 对象中的 HttpEntity。当我使用调试器单步调试时,我可以看到实体有内容(长度> 0),我什至可以查看内容,但我看到的只是一个数字数组(我猜是 ASCII 代码?),这不是有帮助。我将在实体上调用 EntityUtils.toString(),但会返回一个异常 - 要么是 IOException,要么是某种“对象处于无效状态”异常。这真是令人沮丧!有什么方法可以以人类可读的形式获取这些内容吗?

这是我的代码:

    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 的内容并将其放入异常中。

java apache-httpclient-4.x apache-httpcomponents
4个回答
47
投票

Appache 已经提供了一个名为 EntityUtils 的 Util 类。

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

22
投票

以下是一些将实体视为字符串的代码(假设您的请求 contentType 是 html 或类似的):

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

6
投票

要启用人类可读的形式,您可以将 HttpEntity 转换为带有 UTF-8 代码的字符串

EntityUtils.toString(response.getEntity(), "UTF-8")

这将为您提供 json 形式的响应参数,例如:

{ "error": { "errors": [ { "domain": "global", "reason": "forbidden", "message": "Forbidden" } ], "code": 403, "message": "禁止”}}

希望这能解决问题。


1
投票

一般来说,如果您想将 DTO 转换为字符串格式,那么您可以使用 ObjectMapper。如果有帮助,请查找以下示例。

public static String getObjectAsString(Object object) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.writeValueAsString(object);
    } catch (Exception e) {
        return null;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.