如何从CloseableHttpResponse实例获取Status Line?Java类及代码报错问题
解决Apache HttpClient 5.x中获取响应状态行的问题
你遇到的问题是因为Apache HttpClient 5.x版本与4.x版本的API存在兼容性变化,CloseableHttpResponse不再提供getStatusLine()方法,该功能被重构为getStatus()方法,返回HttpStatus类型的对象。
正确的实现方式
修改获取状态行的代码,替换为getStatus()方法,示例如下:
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.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.HttpStatus; // 需要导入这个类 public class Prueba_REST { public static void main(String[] args) throws IOException { // 使用try-with-resources自动关闭资源,避免泄漏 try (CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse httpresponse = httpclient.execute(new HttpGet("https://www.tutorialspoint.com"))) { // 打印请求方法 System.out.println("Request Type: " + HttpGet.METHOD_NAME); // 获取状态信息 HttpStatus status = httpresponse.getStatus(); // 直接打印状态对象,输出格式类似 "HTTP/1.1 200 OK" System.out.println("Status Line: " + status); // 也可以单独获取状态码和原因短语 System.out.println("Status Code: " + status.getStatusCode()); System.out.println("Reason Phrase: " + status.getReasonPhrase()); // 读取响应内容 try (Scanner scanner = new Scanner(httpresponse.getEntity().getContent())) { while (scanner.hasNext()) { System.out.println(scanner.nextLine()); } } } } }
关键说明
- API变化:HttpClient 5.x将原4.x中的
StatusLine替换为HttpStatus接口,通过getStatus()获取状态相关信息 - 资源管理:使用
try-with-resources语法自动关闭CloseableHttpClient、CloseableHttpResponse和Scanner,避免资源泄漏 - 状态信息获取:
- 直接调用
status.toString()(或直接打印status)会返回类似传统StatusLine的字符串(如HTTP/1.1 200 OK) - 调用
getStatusCode()获取数字状态码,getReasonPhrase()获取状态描述短语
- 直接调用
内容的提问来源于stack exchange,提问作者AJHG
相关产品推荐
相关产品推荐

