You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HttpClient返回4xx状态码时获取响应体内容

解决HttpClient 4xx状态码无法获取响应体的问题
  • 不要直接调用HttpClient实例的toString()方法,该方法仅返回客户端实例的标识信息,不会包含响应体内容。
  • 无论响应状态码是成功(2xx)还是客户端/服务端错误(4xx/5xx),都需通过HttpResponse的实体对象读取响应体:
    1. 执行请求后获取CloseableHttpResponse对象
    2. 调用response.getEntity()获取响应实体HttpEntity
    3. 使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 12:25:22