如何从HttpResponse实例获取Entity对象内容?报错求助
问题解决:Apache HttpClient5 获取Entity内容报错
可能的错误原因
- 目标网站返回重定向状态码(如301/302),此时响应无实体内容,
httpresponse.getEntity()返回null,直接调用getContent()会触发NullPointerException - 未正确处理资源关闭,引发IO异常
- 未检查响应状态,直接处理实体导致逻辑错误
修正后的代码
package com.mycompany.prueba_rest; import java.io.IOException; import java.util.Scanner; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpResponse; public class Prueba_REST { public static void main(String[] args) throws IOException { // 使用try-with-resources自动关闭HttpClient资源 try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpGet httpget = new HttpGet("https://www.tutorialspoint.com"); System.out.println("Request Type: " + httpget.getMethod()); HttpResponse httpresponse = httpclient.execute(httpget); int statusCode = httpresponse.getCode(); // 仅处理成功响应(2xx状态码) if (statusCode >= 200 && statusCode < 300) { HttpEntity entity = httpresponse.getEntity(); // 先检查实体是否非空 if (entity != null) { // 使用try-with-resources自动关闭Scanner和流 try (Scanner scanner = new Scanner(entity.getContent())) { while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } } } else { System.out.println("响应无实体内容"); } } else { System.out.println("请求失败,状态码:" + statusCode); } } } }
关键修正点
- 资源自动管理:用
try-with-resources包裹CloseableHttpClient和Scanner,确保资源自动关闭,避免IO泄漏 - 状态码校验:先判断响应状态码是否为成功范围(2xx),再处理实体
- 非空检查:调用
getContent()前先判断HttpEntity是否为null,避免空指针异常
额外说明
你的依赖配置是正确的,无需更换版本。如果仍有问题,检查网络连接是否正常,或目标网站是否有反爬机制限制请求。
内容的提问来源于stack exchange,提问作者AJHG
相关产品推荐
相关产品推荐

