Java HttpClient Timeout – Java HttpClient超时

最后修改: 2022年 5月 25日

1. Overview


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.


2. Configuring a Timeout


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


private static HttpClient getHttpClientWithTimeout(int seconds) {
    return HttpClient.newBuilder()

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.


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


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


3. Handling Timeouts


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


HttpRequest httpRequest = HttpRequest.newBuilder()

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.


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


3.1. Handling Synchronous Call Timeout


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


HttpConnectTimeoutException thrown = assertThrows(
  () -> 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.


3.2. Handling Asynchronous Call Timeout


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


CompletableFuture<String> completableFuture = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString())
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.


4. Configure Timeout at the Request Level


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:


HttpRequest httpRequest = HttpRequest.newBuilder()

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.


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


5. Conclusions


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.