以 String 形式读取 HTTP 响应体
1、简介
本文介绍了以字符串形式读取 HTTP 响应体的几种方式。
2、HttpClient
Java 11 中添加了 HttpClient,用于访问 Web 资源。与 HttpURLConnection 不同的是,HttpClient 除了支持 HTTP/1.1 和 HTTP/2 外,它还提供同步和异步请求类型。
HttpClient 提供了一个现代化的 API,具有很大的灵活性和强大的功能。该 API 由三个核心类组成:HttpClient、HttpRequest 和 HttpResponse。
HttpResponse 描述了 HttpRequest 调用的结果。HttpResponse 并非直接创建,而是在完全接收到正文(Body)后才可用。
首先创建 HttpClient 和 HttpRequest 对象:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(DUMMY_URL))
.build();
然后,使用 BodyHandlers 并调用 ofString() 方法返回 String 响应:
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
3、HttpURLConnection
HttpURLConnection 是一个轻量级 HTTP 客户端,用于通过 HTTP 或 HTTPS 协议访问资源,它允许创建一个 InputStream。获得 InputStream 后,就可以像读取普通本地文件一样读取它。
在 Java 中,可以用来访问互联网的主要类是 java.net.URL 类和 java.net.HttpURLConnection 类。使用 URL 类指向 Web 资源。然后,使用 HttpURLConnection 类访问该资源。
首先使用 URL 创建一个 HttpURLConnection:
HttpURLConnection connection = (HttpURLConnection) new URL(DUMMY_URL).openConnection();
new URL(DUMMY_URL).openConnection() 返回一个 HttpURLConnection。该对象允许我们添加 Header 或检查响应码。
接下来,从 connection 对象中获取 InputStream:
InputStream inputStream = connection.getInputStream();
最后,将 InputStream 转换为 String。
4、Apache HttpClient
首先在 Maven 中添加其依赖:
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2</version>
</dependency>
通过 CloseableHttpClient 类检索和发送数据,首先使用 HttpClients.createDefault() 创建一个具有默认配置的实例。
CloseableHttpClient 提供了一个用于发送和接收数据的 execute 方法。该方法使用 2 个参数。第一个参数是 HttpUriRequest 类型,它有许多子类,包括 HttpGet 和 HttpPost。第二个参数是 HttpClientResponseHandler 类型,用于从 ClassicHttpResponse 生成响应(Response)对象。
首先,创建一个 HttpGet 对象:
HttpGet request = new HttpGet(DUMMY_URL);
其次,创建客户端:
CloseableHttpClient client = HttpClients.createDefault();
最后,从 execute 方法的结果中获取响应对象:
String response = client.execute(request, new BasicHttpClientResponseHandler());
logger.debug("Response -> {}", response);
这里使用了 BasicHttpClientResponseHandler,它以 String 形式返回响应体。
5、Spring RestTemplate
RestTemplate 已被逐渐弃用。因此,应该考虑使用 Spring WebClient,如下一节所述。
RestTemplate 类是 Spring 提供的一个重要工具,它提供了一个简单的模板,用于在底层的 HTTP 客户端库上执行客户端 HTTP 操作,如 JDK的 HttpURLConnection、Apache HttpClient 等。
RestTemplate 为创建 HTTP 请求和处理响应提供了一些有用的方法。
添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
<scope>test</scope>
</dependency>
首先,创建 RestTemplate 实例:
RestTemplate restTemplate = new RestTemplate();
然后,通过调用 getForObject() 方法并传入 URL 和期望的响应类型来获取响应对象。在本例中,使用 String.class 作为响应类型:
String response = restTemplate.getForObject(DUMMY_URL, String.class);
6、Spring WebClient
Spring WebClient,它是取代 Spring RestTemplate 的响应式非阻塞解决方案。
在项目中添加 spring-boot-starter-webflux 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
执行 HTTP Get 请求的最简单方法是使用 create 方法:
WebClient webClient = WebClient.create(DUMMY_URL);
执行 HTTP Get 请求的最简单方法是调用 get 和 retrieve 方法。然后,使用 bodyToMono 方法并指定 String.class 类型,将响应体提取为单个 String 实例:
Mono<String> body = webClient.get().retrieve().bodyToMono(String.class);
最后,调用 block 方法,告诉 WebFlux 等待直到整个响应体流被读取并复制到 String 结果中:
String s = body.block();
7、总结
本文介绍了以 String 形式读取 HTTP 响应体几种方法,包括使用 HttpClient、HttpURLConnection、HttpClient、RestTemplate 和 WebClient。
Ref:https://www.baeldung.com/java-http-response-body-as-string