Sub topic 9
Setting Connect and Request Timeouts
Assume you know Java 11 syntax, checked exceptions, and the basic HttpClient, HttpRequest, and HttpResponse types. A timeout limits how long your program waits for a network operation. Without suitable timeouts, a slow or unreachable server can keep a thread waiting indefinitely.
Two kinds of timeout
Java's HttpClient has two important timeout settings:
- A connect timeout limits the time spent establishing a connection to the server.
- A request timeout limits how long a particular request waits for a response.
Set the connect timeout on the shared client. Set the request timeout on each HttpRequest that needs one.
Configure the client and request
connectTimeout accepts a Duration. This client waits up to five seconds while opening a connection. The request waits up to ten seconds for the server's response.
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 TimeoutExample {
public static void main(String[] args) {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://example.com/"))
.timeout(Duration.ofSeconds(10))
.GET()
.build();
try {
HttpResponse<String> response = client.send(
request,
HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
} catch (java.net.http.HttpTimeoutException e) {
System.err.println("The request timed out");
} catch (java.io.IOException e) {
System.err.println("Network failure: " + e.getMessage());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("The operation was interrupted");
}
}
}A request timeout is not a server-status check. A server can return 500 before the timeout, and send still returns an HttpResponse. Check the status code separately.
Handling timeout failures
HttpTimeoutException is a specialized IOException, so catch it before the general IOException. For asynchronous calls, a timeout usually completes the CompletableFuture exceptionally. Inspect the underlying cause when logging or classifying the failure.
Choose values based on the operation. A short timeout can protect an interactive request, while a file download may need a longer limit. Do not use one extremely large timeout to hide an unreliable service.
Exercise
Where should you configure a five-second connection limit and a ten-second limit for one request?
Show answer
Configure five seconds with HttpClient.newBuilder().connectTimeout(...), and ten seconds with HttpRequest.Builder.timeout(...).