Reading an HTTP Response Body as a String in Java – 在Java中以字符串形式读取HTTP响应体

最后修改: 2020年 9月 29日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this tutorial, we’ll explore several libraries for reading an HTTP response body as a string in Java. Since the first versions, Java has provided the HttpURLConnection API. This includes only basic features, and is known for not being very user-friendly.

在本教程中,我们将探讨在Java中读取作为字符串的HTTP响应体的几个库。从第一个版本开始,Java就提供了HttpURLConnection API。这只包括基本的功能,而且以不太方便用户使用而闻名。

With JDK 11, Java introduced the new and improved HttpClient API to handle HTTP communication. We’ll discuss these libraries, as well as check out alternatives, such as the Apache HttpClient and Spring Rest Template.

在 JDK 11 中,Java 引入了新的和改进的 HttpClientAPI 来处理 HTTP 通信。我们将讨论这些库,以及查看替代方案,例如Apache HttpClientSpring Rest Template

2. HttpClient

2.HttpClient

As previously mentioned, HttpClient was added to Java 11. It allows us to access resources over the network, but unlike HttpURLConnection, HttpClient supports HTTP/1.1 and HTTP/2. Moreover, it provides both synchronous and asynchronous request types.

如前所述,HttpClient被添加到Java 11中。它允许我们通过网络访问资源,但与HttpURLConnection不同,HttpClient支持HTTP/1.1和HTTP/2。此外,它还提供了同步和异步的请求类型

HttpClient offers a modern API with a lot of flexibility and powerful features. This API consists of three core classes: HttpClient, HttpRequest, and HttpResponse.

HttpClient提供了一个具有很多灵活性和强大功能的现代API。这个API由三个核心类组成。HttpClient, HttpRequest, 和HttpResponse

HttpResponse describes the result of an HttpRequest call. HttpResponse isn’t created directly, and is made available when the body has been fully received.

HttpResponse描述的是HttpRequest调用的结果。HttpResponse并不是直接创建的,而是在完全接收了主体后才提供的。

To read a response body as a String, we’ll first need to create simple client and request objects:

为了将响应体读成字符串,我们首先需要创建简单的客户端和请求对象。

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(DUMMY_URL))
    .build();

Then we’ll use BodyHandlers and call the method ofString() to return the response:

然后我们将使用BodyHandlers并调用ofString()方法来返回响应。

HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());

3. HttpURLConnection

3.HttpURLConnection

HttpURLConnection is a lightweight HTTP client used to access resources via the HTTP or HTTPS protocol, and it allows us to create an InputStream. Once we obtain the InputStream, we can read it like a normal local file.

HttpURLConnection是一个轻量级的HTTP客户端,用于通过HTTP或HTTPS协议访问资源,它允许我们创建一个InputStream。一旦我们获得了InputStream,我们就可以像一个普通的本地文件一样读取它。

In Java, the main classes we can use to access the Internet are the java.net.URL class and the java.net.HttpURLConnection class. First, we’ll use the URL class to point to a web resource. Then we can access it by using the HttpURLConnection class.

在Java中,我们可以用来访问互联网的主要类是java.net.URL类和java.net.HttpURLConnection类。首先,我们将使用URL类来指向一个网络资源。然后我们可以通过使用HttpURLConnection类来访问它。

To get the response body from a URL as a String, we should first create an HttpURLConnection using our URL:

为了从URL中获取响应体作为字符串,我们应该首先使用我们的URL创建一个HttpURLConnection

HttpURLConnection connection = (HttpURLConnection) new URL(DUMMY_URL).openConnection();

The new URL(DUMMY_URL).openConnection() returns an HttpURLConnection. This object allows us to add headers or check the response code.

new URL(DUMMY_URL).openConnection()返回一个HttpURLConnection。这个对象允许我们添加头信息或检查响应代码。

Next, we’ll get the InputStream from the connection object:

接下来,我们将connection对象中获取InputStream

InputStream inputStream = connection.getInputStream();

Finally, we need to convert the InputStream to a String.

最后,我们需要InputStream转换为String

4. Apache HttpClient

4.阿帕奇HttpClient

In this section, we’ll learn how to use the Apache HttpClient for reading an HTTP response body as a string.

在本节中,我们将学习如何使用Apache HttpClient来读取作为字符串的HTTP响应体。

To use this library, we’ll need to add its dependency to our Maven project:

为了使用这个库,我们需要在Maven项目中添加其依赖关系。

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>

We can retrieve and send data via the CloseableHttpClient class. To create an instance of it with the default configuration, we can use the HttpClients.createDefault().

我们可以通过CloseableHttpClient类来检索和发送数据。为了用默认配置创建它的实例,我们可以使用HttpClients.createDefault()

CloseableHttpClient provides an execute method to send and receive data. This method uses a parameter of type HttpUriRequest, which has many subclasses, including HttpGet and HttpPost.

CloseableHttpClient提供了一个execute方法来发送和接收数据。这个方法使用一个HttpUriRequest类型的参数,它有许多子类,包括HttpGetHttpPost

First, we’ll create an HttpGet object:

首先,我们将创建一个HttpGet对象

HttpGet request = new HttpGet(DUMMY_URL);

Second, we’ll create the client:

第二,我们将创建客户端

CloseableHttpClient client = HttpClients.createDefault();

Then we’ll retrieve the response object from the result of the execute method:

然后我们将从执行方法的结果中检索响应对象

CloseableHttpResponse response = client.execute(request);

Finally, we’ll return the response body by converting the response entity to a String:

最后,我们将通过将响应实体转换为String返回响应体。

HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);

5. Spring RestTemplate

5.SpringRestTemplate

In this section, we’ll demonstrate how to use Spring RestTemplate to read an HTTP response body as a string. We must note that RestTemplate is now deprecated. As such, we should consider using Spring WebClient, as described in the next section.

在本节中,我们将演示如何使用Spring RestTemplate来读取作为字符串的HTTP响应体。我们必须注意,RestTemplate现在已经被废弃了。因此,我们应该考虑使用Spring WebClient,如下节所述。

The RestTemplate class is an essential tool provided by Spring that offers a simple template for making client-side HTTP operations over underlying HTTP client libraries, such as JDK HttpURLConnection, Apache HttpClient, and others.

RestTemplate类是Spring提供的一个重要工具,它提供了一个简单的模板,用于在底层HTTP客户端库(如JDK HttpURLConnection、Apache HttpClient等)上进行客户端HTTP操作。

RestTemplate provides some useful methods for creating HTTP requests and handling responses.

RestTemplate提供一些有用的方法用于创建HTTP请求和处理响应。

We can use this library by first adding some dependencies to our Maven project:

我们可以通过向Maven项目添加一些依赖项来使用这个库。

<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>

To make a web request and return the response body as a string, we’ll create an instance of RestTemplate:

为了发出一个Web请求并以字符串形式返回响应体,我们将创建一个RestTemplate的实例。

RestTemplate restTemplate = new RestTemplate();

Then we’ll get the response object by calling the method getForObject(), and passing in the URL and desired response type. We’ll use String.class in our example:

然后我们将通过调用getForObject()方法获得响应对象,并传入URL和所需的响应类型。我们将在我们的例子中使用String.class

String response = restTemplate.getForObject(DUMMY_URL, String.class);

6. Spring WebClient

6. Spring WebClient

Finally, we’ll see how to use Spring WebClient, the reactive, non-blocking solution replacing Spring RestTemplate.

最后,我们将看到如何使用Spring WebClient,反应式、非阻塞式解决方案,取代Spring RestTemplate

We can use this library by adding the spring-boot-starter-webflux dependency to our Maven project:

我们可以通过在Maven项目中添加spring-boot-starter-webflux依赖项来使用该库。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

The simplest way to perform an HTTP Get request is to use the create method:

执行HTTP Get请求的最简单方法是使用create方法。

WebClient webClient = WebClient.create(DUMMY_URL);

The simplest way to perform an HTTP Get request is to call the get and retrieve methods. Then we’ll use the bodyToMono method with the String.class type to extract the body as a single String instance:

执行HTTP Get请求的最简单方法是调用getretrieve方法。然后我们使用bodyToMono方法与String.class类型来提取身体作为一个单一的String实例。

Mono<String> body = webClient.get().retrieve().bodyToMono(String.class);

Finally, we’ll call the block method to tell the web flux to wait until the whole body stream is read and copied in the String result:

最后,我们将调用block方法来告诉web flux等待,直到整个body stream被读取并复制到String结果中。

String s = body.block();

7. Conclusion

7.结语

In this article, we learned how to use several libraries for reading an HTTP response body as a String.

在这篇文章中,我们学习了如何使用几个库来读取作为String的HTTP响应体。

As usual, the complete code is available over on GitHub.

像往常一样,完整的代码可以在GitHub上找到