How do I set a timeout on HTTP requests in Java 11?

To set a timeout on HTTP requests in Java 11, you can use the HttpClient provided by the java.net.http module. The HttpClient API allows you to configure timeouts for requests in a convenient and standardized way.

Here’s how you can do it:

  1. Set a Connection Timeout: This controls the timeout when establishing a connection to the target server.
  2. Set a Read Timeout: This sets the timeout for reading data once the connection is established.

Here is an example demonstrating how to configure both:

Code Example

package org.kodejava.net.http;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class HttpTimeoutExample {
   public static void main(String[] args) {
      // Create an HttpClient with a timeout configuration
      HttpClient client = HttpClient.newBuilder()
              .connectTimeout(Duration.ofSeconds(5)) // Set connection timeout
              .build();

      // Create an HttpRequest
      HttpRequest request = HttpRequest.newBuilder()
              .uri(URI.create("https://example.com"))
              .timeout(Duration.ofSeconds(10)) // Set request timeout
              .GET()
              .build();

      try {
         // Send the request and receive the response
         HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
         System.out.println("Response status code: " + response.statusCode());
         System.out.println("Response body: " + response.body());
      } catch (Exception e) {
         System.err.println("Request failed: " + e.getMessage());
      }
   }
}

Explanation

  1. Connection Timeout:
    • Configured on the HttpClient with connectTimeout(Duration).
    • This defines how long the client will wait while attempting to establish a connection with the server.
  2. Request Timeout:
    • Configured on the HttpRequest with timeout(Duration).
    • This defines how long the request will wait for a complete response after connection establishment.
  3. Error Handling:
    • For failed requests (e.g., timeouts), you should catch and handle exceptions like java.net.http.HttpTimeoutException or log a generic failure as shown above.

Notes

  • If either of the timeouts is exceeded, you will get an exception that can be handled to retry, alert, or further process as needed.
  • Both settings are optional. If not configured, the client will use default timeouts per its implementation.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.