Course – LS (cat=HTTP Client-Side)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:


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.

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

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.

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

Course – LS (cat=HTTP Client-Side)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:


res – HTTP Client (eBook) (cat=Http Client-Side)