25

我一直遇到这种情况,我得到一个错误的 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 的内容并将其放入异常中。

4

4 回答 4

45

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

String responseXml = EntityUtils.toString(httpResponse.getEntity());
EntityUtils.consume(httpResponse.getEntity());
于 2016-10-11T13:36:22.483 回答
21

下面是一些将实体视为字符串的代码(假设您的请求 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();
  }
于 2011-08-31T22:29:54.010 回答
5

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

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

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

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

希望这能解决问题。

于 2018-07-11T15:27:00.863 回答
1

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

public static String getObjectAsString(Object object) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.writeValueAsString(object);
    } catch (Exception e) {
        return null;
    }
}
于 2019-05-31T10:18:00.333 回答