如何在HttpClient返回4xx状态码时获取响应体内容
解决HttpClient 4xx状态码无法获取响应体的问题
- 不要直接调用
HttpClient实例的toString()方法,该方法仅返回客户端实例的标识信息,不会包含响应体内容。 - 无论响应状态码是成功(2xx)还是客户端/服务端错误(4xx/5xx),都需通过
HttpResponse的实体对象读取响应体:- 执行请求后获取
CloseableHttpResponse对象 - 调用
response.getEntity()获取响应实体HttpEntity - 使用
EntityUtils.toString(entity)读取完整响应体,建议指定编码格式避免乱码
- 执行请求后获取
示例代码
CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("目标请求URL"); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { // 读取响应体 HttpEntity entity = response.getEntity(); if (entity != null) { String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8); // 可将responseBody解析为JSON或做其他处理 System.out.println("响应体:" + responseBody); } // 获取状态码 int statusCode = response.getStatusLine().getStatusCode(); System.out.println("状态码:" + statusCode); } catch (IOException e) { e.printStackTrace(); }
- 注意:若你的代码中配置了自动抛出
HttpResponseException的拦截器,需调整拦截逻辑,避免在读取响应体前中断请求流程。
内容的提问来源于stack exchange,提问作者David Agostini
相关产品推荐
相关产品推荐

