Java HttpClient Timeout – Java HttpClient超时

最后修改: 2022年 5月 25日

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

1. Overview

1.概述

In this tutorial, we’ll show how to set up a timeout with the new Java HTTP client available from Java 11 onwards and the Java.

在本教程中,我们将展示如何使用从Java 11开始提供的新的Java HTTP客户端和Java.Net设置超时。

In case we need to refresh our knowledge, we can start with the tutorial on Java HTTP Client.

如果我们需要复习知识,我们可以从Java HTTP客户端的教程开始。

On the other hand, to learn how to set up a timeout using the older library, see HttpUrlConnection.

另一方面,要学习如何使用旧的库来设置超时,请参阅HttpUrlConnection.

2. Configuring a Timeout

2.配置超时

First of all, we need to set up an HttpClient to be able to make an HTTP request:

首先,我们需要设置一个HttpClient,以便能够进行HTTP请求。

private static HttpClient getHttpClientWithTimeout(int seconds) {
    return HttpClient.newBuilder()
      .connectTimeout(Duration.ofSeconds(seconds))
      .build();
}

Above, we created a method that returns a HttpClient configured with a timeout defined as a parameter. Shortly, we use the Builder design pattern to instantiate an HttpClient and configure the timeout using the connectTimeout method. Additionally, using the static method ofSeconds, we created an instance of the Duration object that defines our timeout in seconds.

上面,我们创建了一个方法,该方法返回一个HttpClient,并配置了一个定义为参数的超时。不久,我们使用Builder设计模式来实例化一个HttpClient并使用connectTimeout方法来配置超时时间。此外,使用静态方法ofSeconds,我们创建了一个Duration对象的实例,以秒为单位定义了我们的超时。

After that, we check if the HttpClient timeout is configured correctly:

之后,我们检查HttpClient超时是否被正确配置。

httpClient.connectTimeout().map(Duration::toSeconds)
  .ifPresent(sec -> System.out.println("Timeout in seconds: " + sec));

So, we use the connectTimeout method to get the timeout. As a result, it returns an Optional of Duration, which we mapped to seconds.

因此,我们使用connectTimeout方法来获取超时。结果,它返回一个OptionalDuration,我们将其映射为秒。

3. Handling Timeouts

3.处理超时

Further, we need to create an HttpRequest object that our client will use to make an HTTP request:

此外,我们需要创建一个HttpRequest对象,我们的客户将用它来进行HTTP请求。

HttpRequest httpRequest = HttpRequest.newBuilder()
  .uri(URI.create("http://10.255.255.1")).GET().build();

To simulate a timeout, we make a call to a non-routable IP address. In other words, all the TCP packets drop and force a timeout after the predefined duration as configured earlier.

为了模拟超时,我们调用了一个不可路由的IP地址。换句话说,所有的TCP数据包都会在前面配置的预定义时间后丢弃并强制超时。

Now, let’s take a deeper look at how to handle a timeout.

现在,让我们更深入地看看如何处理超时的问题。

3.1. Handling Synchronous Call Timeout

3.1.处理同步呼叫超时

For example, to make the synchronous call use the send method:

例如,为了进行同步调用,使用send方法。

HttpConnectTimeoutException thrown = assertThrows(
  HttpConnectTimeoutException.class,
  () -> httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()),
  "Expected send() to throw HttpConnectTimeoutException, but it didn't");
assertTrue(thrown.getMessage().contains("timed out"));

The synchronous call forces to catch the IOException, which the HttpConnectTimeoutException extends. Consequently, in the test above, we expect the HttpConnectTimeoutException with an error message.

同步调用强制捕捉IOException,而HttpConnectTimeoutException扩展了。因此,在上面的测试中,我们期待HttpConnectTimeoutException的错误信息。

3.2. Handling Asynchronous Call Timeout

3.2.处理异步调用超时

Similarly, to make the asynchronous call use the sendAsync method:

同样地,要进行异步调用,请使用sendAsync方法。

CompletableFuture<String> completableFuture = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString())
  .thenApply(HttpResponse::body)
  .exceptionally(Throwable::getMessage);
String response = completableFuture.get(5, TimeUnit.SECONDS);
assertTrue(response.contains("timed out"));

The above call to sendAsync returns a CompletableFuture<HttpResponse>. Consequently, we need to define how to handle the response functionally. In detail, we get the body from the response when no error occurs. Otherwise, we get the error message from the throwable. Finally, we get the result from the CompletableFuture by waiting a maximum of 5 seconds. Again, this request throws an HttpConnectTimeoutException as we expect just after 3 seconds.

上述对sendAsync的调用返回一个CompletableFuture<HttpResponse>。因此,我们需要定义如何在功能上处理该响应。详细来说,当没有错误发生时,我们从响应中获得正文。否则,我们从throwable中获得错误信息。最后,我们从CompletableFuture中获得结果,最多等待5秒。同样,这个请求抛出了一个HttpConnectTimeoutException,正如我们所期望的那样,在3秒之后就会出现。

4. Configure Timeout at the Request Level

4.在请求层配置超时

Above, we reused the same client instance for both the sync and async call. However, we might want to handle the timeout differently for each request. Likewise, we can set up the timeout for a single request:

上面,我们在syncasync调用中都重用了同一个客户端实例。然而,我们可能想对每个请求的超时进行不同的处理。同样地,我们可以为单个请求设置超时。

HttpRequest httpRequest = HttpRequest.newBuilder()
  .uri(URI.create("http://10.255.255.1"))
  .timeout(Duration.ofSeconds(1))
  .GET()
  .build();

Similarly, we are using the timeout method to set up the timeout for this request. Here, we configured the timeout of 1 second for this request.

同样,我们使用timeout方法来设置这个请求的超时。这里,我们为这个请求配置了1秒的超时。

The minimum duration between the client and the request sets the timeout for the request.

客户端和请求之间的最小持续时间设置请求的超时。

5. Conclusions

5.结论

In this article, we successfully configure a timeout using the new Java HTTP Client and handle a request gracefully when timeouts overflow.

在这篇文章中,我们使用新的Java HTTP客户端成功地配置了一个超时,并在超时溢出时优雅地处理一个请求。

And as always, the source code for the examples is available over on GitHub.

像往常一样,这些例子的源代码可以在GitHub上找到