All 15 Java Networking & HTTP Client questions
More in Java Networking & HTTP Client
Advertisement
Java › Java Networking & HTTP Client

How would you configure HttpClient with custom timeouts, a proxy, and connection pooling behavior, and what's the difference between a connection timeout and a request/response timeout?

Intermediate

Answer

HttpClient.newBuilder() lets you configure a connectTimeout (maximum time to establish the initial TCP/TLS connection) at the client level, while an individual HttpRequest.Builder's timeout() sets a per-request timeout (maximum time to wait for the complete request/response exchange) -- these are conceptually distinct: a connection timeout failure means the target server couldn't even be reached/connected to in time, while a request timeout failure means the connection succeeded but the server took too long to respond; HttpClient also supports configuring an explicit proxy (via ProxySelector) and internally manages connection pooling/reuse (particularly beneficial for HTTP/2's connection multiplexing) automatically without requiring explicit manual configuration for typical use cases.
HttpClient client = HttpClient.newBuilder()
    .connectTimeout(Duration.ofSeconds(5))   // max time to establish the connection itself
    .proxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 8080)))
    .build();

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/data"))
    .timeout(Duration.ofSeconds(10))          // max time for THIS specific request/response exchange
    .build();
Real-world example A service calling a historically slow, occasionally unresponsive downstream API configures both a short connectTimeout (5 seconds, since an unreachable server should fail fast) and a more generous per-request timeout (30 seconds, allowing genuinely slow-but-working responses time to complete), correctly distinguishing these two different failure modes with appropriately different tolerances.

Common follow-ups: What happens to an in-flight request if the configured timeout is exceeded -- what specific exception is thrown?;How does HttpClient's connection pooling and reuse behavior differ between HTTP/1.1 and HTTP/2 protocol versions?