HTTP client and timeouts
What you will learn
HttpClient sends immutable HttpRequest values and returns HttpResponse values with a status, headers, protocol version and body. A client can reuse connections across requests. A successful transport exchange is not necessarily a successful application operation: inspect the status and validate the body.
- Build and send local HTTP requests synchronously and asynchronously.
- Distinguish connect, request and caller wait timeouts.
- Handle status, redirects, body ownership and cancellation.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Use only the included loopback peers and finite known messages. Port 0 selects a test-owned port. Do not expose the fixtures publicly. The runner enforces a process deadline.
Send a synchronous request
import java.io.*;import java.net.*;import java.net.http.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.*;import java.util.concurrent.*;import com.sun.net.httpserver.HttpServer;public class Main { static HttpServer server() throws IOException { // Numeric IPv4 loopback; port 0 chooses an available lab port. HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 1); server.createContext("/stock", exchange -> { try (exchange) { byte[] body = "stock=3".getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=UTF-8"); exchange.sendResponseHeaders(200, body.length); exchange.getResponseBody().write(body); } }); server.createContext("/move", exchange -> { try (exchange) { exchange.getResponseHeaders().set("Location", "/stock"); exchange.sendResponseHeaders(302, -1); } }); server.start(); return server; } static HttpClient client() { return HttpClient.newBuilder().proxy(ProxySelector.of(null)) .version(HttpClient.Version.HTTP_1_1) .followRedirects(HttpClient.Redirect.NEVER) .connectTimeout(Duration.ofSeconds(2)).build(); } static HttpRequest request(HttpServer server, String path) { // Only fixed paths supplied by the lab, not arbitrary URLs. return HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + server.getAddress().getPort() + path)) .timeout(Duration.ofSeconds(3)).GET().build(); } public static void main(String[] args) throws Exception { HttpServer server = server(); try (HttpClient client = client()) { var result = client.send(request(server, "/stock"), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); System.out.println(result.statusCode()); System.out.println(result.version()); System.out.println(result.body()); } finally { server.stop(0); } }}Expected output:
200HTTP_1_1stock=3The test server has a fixed response. The actual HTTP version and status are observed, not inferred from the request.
URI, URL and HTTP semantics
URI describes a resource identifier and can be resolved or normalized without opening a connection. URL is a locator with protocol-related operations; prefer URI construction and toURL when necessary rather than deprecated URL constructors in modern Java. A parsed URI is not an authorization decision. HTTP methods, headers and bodies express requests; 2xx, 3xx, 4xx and 5xx describe different classes of status. A 404 is a response, not automatically an IOException. HTTPS adds TLS; certificate trust and hostname verification are required. Do not disable either. The next chapter covers trust configuration.
Own the client and the body
HttpClient arrived in Java 11; Java 21 adds AutoCloseable and shutdown APIs. Keep a client at a service or operation owner boundary rather than creating one per production request. The fixture uses an explicitly closed Java 21 client and a JDK-specific local HttpServer. BodyHandlers.ofString aggregates the entire body; use it only for known tiny responses here. For untrusted content, use bounded streaming or a size-enforcing subscriber; close or drain streaming bodies and enforce body deadlines. A Content-Length header alone is not a reliable size limit.
Deadlines and redirects
connectTimeout applies to establishing a new connection, not reusing one. Request timeout and a Future.get timeout are different: the latter bounds caller waiting, and does not by itself cancel the exchange. Streaming-body lifetime requires its own controls; do not treat a request timeout as a universal read deadline across JDK versions and handlers. Cancellation is best effort; server-side effects may already have occurred. Avoid automatic redirects for fixed internal destinations; validate each allowed target before following. HTTP/1.1 and HTTP/2 preference is not a guarantee of the negotiated version; inspect response.version().
Handle missing resources and redirects
import java.io.*;import java.net.*;import java.net.http.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.*;import java.util.concurrent.*;import com.sun.net.httpserver.HttpServer;public class Main { static HttpServer server() throws IOException { // Numeric IPv4 loopback; port 0 chooses an available lab port. HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 1); server.createContext("/stock", exchange -> { try (exchange) { byte[] body = "stock=3".getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=UTF-8"); exchange.sendResponseHeaders(200, body.length); exchange.getResponseBody().write(body); } }); server.createContext("/move", exchange -> { try (exchange) { exchange.getResponseHeaders().set("Location", "/stock"); exchange.sendResponseHeaders(302, -1); } }); server.start(); return server; } static HttpClient client() { return HttpClient.newBuilder().proxy(ProxySelector.of(null)) .version(HttpClient.Version.HTTP_1_1) .followRedirects(HttpClient.Redirect.NEVER) .connectTimeout(Duration.ofSeconds(2)).build(); } static HttpRequest request(HttpServer server, String path) { // Only fixed paths supplied by the lab, not arbitrary URLs. return HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + server.getAddress().getPort() + path)) .timeout(Duration.ofSeconds(3)).GET().build(); } public static void main(String[] args) throws Exception { HttpServer server = server(); try (HttpClient client = client()) { var pending = client.sendAsync(request(server, "/missing"), HttpResponse.BodyHandlers.discarding()); try { System.out.println(pending.get(4, TimeUnit.SECONDS).statusCode()); } finally { if (!pending.isDone()) pending.cancel(true); } var moved = client.send(request(server, "/move"), HttpResponse.BodyHandlers.discarding()); System.out.println(moved.statusCode()); System.out.println(moved.headers().firstValue("Location").orElseThrow()); } finally { server.stop(0); } }}Expected output:
404302/stockA 404 completes the future normally. Redirect.NEVER preserves the 302 response and Location header.
Bound a request waiting for headers
import java.io.*;import java.net.*;import java.net.http.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.*;import java.util.concurrent.*;import com.sun.net.httpserver.HttpServer;public class Main { static HttpServer server() throws IOException { // Numeric IPv4 loopback; port 0 chooses an available lab port. HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 1); server.createContext("/stock", exchange -> { try (exchange) { byte[] body = "stock=3".getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=UTF-8"); exchange.sendResponseHeaders(200, body.length); exchange.getResponseBody().write(body); } }); server.createContext("/move", exchange -> { try (exchange) { exchange.getResponseHeaders().set("Location", "/stock"); exchange.sendResponseHeaders(302, -1); } }); server.start(); return server; } static HttpClient client() { return HttpClient.newBuilder().proxy(ProxySelector.of(null)) .version(HttpClient.Version.HTTP_1_1) .followRedirects(HttpClient.Redirect.NEVER) .connectTimeout(Duration.ofSeconds(2)).build(); } static HttpRequest request(HttpServer server, String path) { // Only fixed paths supplied by the lab, not arbitrary URLs. return HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + server.getAddress().getPort() + path)) .timeout(Duration.ofSeconds(3)).GET().build(); } public static void main(String[] args) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 1); CountDownLatch release = new CountDownLatch(1); server.createContext("/wait", exchange -> { try (exchange) { try { release.await(5, TimeUnit.SECONDS); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } }); server.start(); try (HttpClient client = client()) { var req = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/wait")) .timeout(Duration.ofMillis(700)).build(); try { client.send(req, HttpResponse.BodyHandlers.discarding()); throw new AssertionError("expected timeout"); } catch (HttpTimeoutException ex) { System.out.println("timed out"); } finally { release.countDown(); } } finally { release.countDown(); server.stop(0); } }}Expected output:
timed outThe server deliberately sends no response headers until the caller finishes; the client timeout is observed without an external host. The server handler has an independent upper bound.
Common mistakes
Do not treat every completed future as a successful business operation, follow arbitrary redirects, assume timeout means the server did nothing, or read an unlimited remote body into a String. Do not disable TLS verification to fix certificate problems.
Practice
Request /stock asynchronously and map the result to a success flag only if status is 200 and body is stock=3. Wait at most four seconds and cancel unfinished work.
Expected output:
trueCompare your answer with the manual practice criteria.
Official reading: URI · HttpClient · HttpRequest.Builder · HttpServer. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP client and timeouts — knowledge check
Original networking and HTTP questions.
What happens for a valid HTTP 404 response?
What does connectTimeout bound?
What does a timed Future.get do when it times out?
Why avoid unrestricted ofString on untrusted responses?
What should a caller inspect to know the response protocol?