Timeouts and checking status codes
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)When a payment or SMS provider hangs, a ShopLite screen can freeze and, in a web app, so can every thread. A safe client limits each wait and checks the status code before it trusts the body.
Connect timeout and request timeout
A timeout is the longest time your code agrees to wait. HttpClient has two: the connect timeout (opening the connection) and the request timeout (waiting for the response). When one runs out, send throws an exception.
Set the connect timeout once on the client and the request timeout on each request. A slow or silent server then gives an exception instead of an endless wait.
Example 1 · A request timeout stops a slow call
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.net.http.HttpTimeoutException;import java.time.Duration;
/** A stand-in API whose report endpoint takes 1.5 seconds, like a busy server. */class SlowApi { static HttpServer start() throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/reports/daily-revenue", exchange -> { try { Thread.sleep(1500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } exchange.sendResponseHeaders(204, -1); exchange.close(); }); server.start(); return server; }}
public class TimeoutDemo { private static final HttpClient CLIENT = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(2)) // max time to open the connection .build();
public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = SlowApi.start(); URI report = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/reports/daily-revenue"); try { HttpRequest request = HttpRequest.newBuilder(report) .timeout(Duration.ofMillis(500)) // max wait for the response .build(); long start = System.nanoTime(); try { CLIENT.send(request, HttpResponse.BodyHandlers.discarding()); System.out.println("Got the report"); } catch (HttpTimeoutException e) { long waitedMs = (System.nanoTime() - start) / 1_000_000; System.out.println("HttpTimeoutException: " + e.getMessage()); System.out.println("Gave up before the server's 1.5 s answer: " + (waitedMs < 1500)); } } finally { server.stop(0); } }}HttpTimeoutException: request timed out Gave up before the server's 1.5 s answer: true
What this code does
- The client has a 2 s connect timeout; the request has a 500 ms timeout. The test server needs 1.5 s, so
sendgives up first and throwsHttpTimeoutException. - Without
.timeout(...)the same call would simply wait 1.5 s, or forever if the server never answered.
Example 2 · A connect timeout against an address that never answers
import java.io.IOException;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpConnectTimeoutException;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.time.Duration;
public class ConnectTimeoutDemo { public static void main(String[] args) throws InterruptedException { HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(2)) .build(); // 10.255.255.1 is a private address that nobody answers: the connection never opens HttpRequest request = HttpRequest.newBuilder(URI.create("http://10.255.255.1/api/v1/products")) .timeout(Duration.ofSeconds(5)) .build();
long start = System.nanoTime(); try { client.send(request, HttpResponse.BodyHandlers.ofString()); } catch (HttpConnectTimeoutException e) { System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage()); } catch (IOException e) { System.out.println("Other network error: " + e); } System.out.println("Waited about " + (System.nanoTime() - start) / 1_000_000_000 + " s"); }}HttpConnectTimeoutException: HTTP connect timed out Waited about 2 s
What this code does
- Nothing answers at
10.255.255.1, so the TCP connection never opens. After the 2 s connect timeout,sendthrowsHttpConnectTimeoutException. - It is caught before the general
IOExceptionbecause it is the more specific type. On some networks a router refuses such addresses at once, and you get aConnectExceptioninstead.
The connect timeout is set with HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)). The request timeout is set with HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(3)). A slow response gives HttpTimeoutException: request timed out; a server that never accepts the connection gives HttpConnectTimeoutException, a subclass of it. Both are IOExceptions, so a catch (IOException e) also catches them.
Pick values from what users can bear: 1 to 3 seconds to connect, a few seconds for a normal request, longer only for known slow endpoints such as reports. The request timeout is per request, so one client can serve both.
ofFile or a streaming body handler and keep the bodies small elsewhere.Why the default "wait forever" is dangerous
By default HttpClient has no timeouts at all: no connect timeout and no request timeout. If the other server accepts the connection and then hangs, send waits forever, and so does the thread that called it.
import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;
public class DefaultsSnippet { public static void main(String[] args) { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8080/api/v1/products")).build();
System.out.println("Connect timeout: " + client.connectTimeout()); System.out.println("Request timeout: " + request.timeout()); System.out.println("Redirects: " + client.followRedirects()); System.out.println("HTTP version: " + client.version()); }}Connect timeout: Optional.empty Request timeout: Optional.empty Redirects: NEVER HTTP version: HTTP_2
- A console app freezes and the user sees nothing, not even an error.
- In a web server, each hung call holds one thread. When the payment or SMS provider hangs during a college-fest rush, all threads end up waiting and your whole app stops answering.
- The fix costs two lines:
connectTimeouton the client andtimeouton every request. Treat a missing timeout as a bug in code review.
Checking statusCode before using the body
A status code is the three-digit number at the start of an HTTP response that says how the call went: 2xx success, 3xx redirect, 4xx a mistake in the request, 5xx a failure on the server.
Read statusCode() first, then decide how to read the body. With 200 the body is data; with 404 or 503 it is an error message, often in another format.
Example 3 · Trusting the body versus checking the status
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;
/** Stock as plain text: 40 for product 1, 404 for product 99, 503 while product 5 is being updated. */class StockApi { static HttpServer start() throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/products/", exchange -> { String id = exchange.getRequestURI().getPath().split("/")[4]; // /api/v1/products/{id}/stock int status = switch (id) { case "1" -> 200; case "5" -> 503; default -> 404; }; String text = switch (status) { case 200 -> "40"; case 503 -> "Service Unavailable: stock update running"; default -> "Not Found"; }; byte[] body = text.getBytes(StandardCharsets.UTF_8); exchange.sendResponseHeaders(status, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }); server.start(); return server; }}
public class StatusCheckDemo { private static final HttpClient CLIENT = HttpClient.newHttpClient();
static HttpResponse<String> getStock(String base, int id) throws IOException, InterruptedException { HttpRequest request = HttpRequest.newBuilder(URI.create(base + "/api/v1/products/" + id + "/stock")).build(); return CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); }
public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = StockApi.start(); String base = "http://127.0.0.1:" + server.getAddress().getPort(); try { System.out.println("Trusting the body:"); for (int id : new int[] {1, 5}) { try { int stock = Integer.parseInt(getStock(base, id).body()); // no status check System.out.println(" product " + id + ": " + stock + " in stock"); } catch (NumberFormatException e) { System.out.println(" product " + id + ": crashed with " + e.getMessage()); } }
System.out.println("Checking the status first:"); for (int id : new int[] {1, 5, 99}) { HttpResponse<String> response = getStock(base, id); int status = response.statusCode(); if (status == 200) { System.out.println(" product " + id + ": " + Integer.parseInt(response.body()) + " in stock"); } else if (status == 404) { System.out.println(" product " + id + ": no such product"); } else if (status >= 500) { System.out.println(" product " + id + ": server problem (" + status + "), try again later"); } else { System.out.println(" product " + id + ": unexpected status " + status); } } } finally { server.stop(0); } }}Trusting the body: product 1: 40 in stock product 5: crashed with For input string: "Service Unavailable: stock update running" Checking the status first: product 1: 40 in stock product 5: server problem (503), try again later product 99: no such product
What this code does
- The first loop parses every body as a number. For product 5 the server is busy (
503) and the body is a text message, soparseIntcrashes with a confusingNumberFormatException. - The second loop reads
statusCode()first and gives each case its own clear message: data for 200, "no such product" for 404, "try again later" for 5xx.
send returns normally for every status, so code written against a working server never sees the problem. Then one day the server answers 503 Service Unavailable with an HTML or text page, and your Integer.parseInt(body) or JSON parsing crashes with a confusing message far from the real cause.
A simple order works well:
- 2xx: read the data.
- 404: "not found" is often a normal answer.
- other 4xx: your request is wrong, so log it and do not retry.
- 5xx: the server failed, so a later retry may work.
Predict the output
Which branch runs?
Read the code and pick what it prints.
Round 1 of 2
The server is restarting and answers 503 with an HTML page. What prints?
Redirect policy and HTTP version
Redirect.NORMAL is a client setting that follows a 3xx redirect to the address in its Location header, except from HTTPS to HTTP. The default, Redirect.NEVER, returns the 301 or 302 itself.
A redirect is a 3xx response that says "look over there". Set followRedirects(HttpClient.Redirect.NORMAL) on the client to follow it.
Example 4 · Redirect.NEVER versus Redirect.NORMAL
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.time.Duration;
/** The old URL /api/products/9 has moved to /api/v1/products/9 (301 Moved Permanently). */class MovedApi { static HttpServer start() throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/products/", exchange -> { String id = exchange.getRequestURI().getPath().substring("/api/products/".length()); exchange.getResponseHeaders().set("Location", "/api/v1/products/" + id); exchange.sendResponseHeaders(301, -1); exchange.close(); }); server.createContext("/api/v1/products/", exchange -> { byte[] body = "{\"id\":9,\"name\":\"Clean Code\"}".getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "application/json"); exchange.sendResponseHeaders(200, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }); server.start(); return server; }}
public class RedirectDemo { public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = MovedApi.start(); URI oldUrl = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/products/9"); try { HttpClient strict = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(2)) .build(); // Redirect.NEVER is the default HttpResponse<String> first = strict.send(HttpRequest.newBuilder(oldUrl).build(), HttpResponse.BodyHandlers.ofString()); System.out.println("NEVER: " + first.statusCode() + ", Location " + first.headers().firstValue("Location").orElse("-"));
HttpClient following = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(2)) .followRedirects(HttpClient.Redirect.NORMAL) // follow, but never https -> http .version(HttpClient.Version.HTTP_1_1) .build(); HttpResponse<String> last = following.send(HttpRequest.newBuilder(oldUrl).build(), HttpResponse.BodyHandlers.ofString()); System.out.println("NORMAL: " + last.statusCode() + " from " + last.uri().getPath() + ", " + last.body()); System.out.println(" redirected from status " + last.previousResponse().map(HttpResponse::statusCode).orElse(0) + ", spoke " + last.version()); } finally { server.stop(0); } }}NEVER: 301, Location /api/v1/products/9
NORMAL: 200 from /api/v1/products/9, {"id":9,"name":"Clean Code"}
redirected from status 301, spoke HTTP_1_1What this code does
- With the default policy the client returns the
301itself, with the new address inLocation. - With
Redirect.NORMALit follows theLocationand returns the final200.uri()shows where it ended, andpreviousResponse()keeps the301. version(HTTP_1_1)makes the client skip the HTTP/2 upgrade attempt;version()on the response confirms what was used.
Redirect.ALWAYS also follows HTTPS to HTTP, so avoid it. After a followed redirect, response.uri() is the final address and response.previousResponse() holds the 3xx answer. Use NORMAL for public APIs that move URLs; keep NEVER when a redirect means something you must handle, such as an expired login.
version(HttpClient.Version.HTTP_1_1) fixes the protocol version. The default, HTTP_2, tries HTTP/2 and falls back to HTTP/1.1 when the server does not support it, so you rarely need to change it. Set HTTP_1_1 only for an old server or proxy that cannot handle the HTTP/2 upgrade attempt.
Turning 4xx and 5xx into meaningful exceptions
Turn each non-2xx response into an exception that names the problem: NotFoundException for 404, ServerErrorException for 5xx and a general ApiException for the rest.
Example 5 · Status codes become exceptions in one place
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.time.Duration;
/** Any non-2xx answer from the API. Keeps the status and the body for logs. */class ApiException extends RuntimeException { private final int status;
ApiException(String message, int status) { super(message); this.status = status; }
int status() { return status; }}
/** 404: the thing we asked for does not exist. */class NotFoundException extends ApiException { NotFoundException(String what) { super(what + " not found", 404); }}
/** 5xx: the server failed; trying again later may work. */class ServerErrorException extends ApiException { ServerErrorException(String method, URI uri, int status) { super(method + " " + uri.getPath() + " failed on the server with " + status, status); }}
/** Stand-in API: product 1 exists, others are 404, product 5 gives 503, a bad id gives 400. */class ProductApi { static HttpServer start() throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/products/", exchange -> { String id = exchange.getRequestURI().getPath().substring("/api/v1/products/".length()); int status = id.equals("1") ? 200 : id.equals("5") ? 503 : id.matches("\\d+") ? 404 : 400; byte[] body = (status == 200 ? "{\"id\":1,\"name\":\"Redmi Note 13 5G\"}" : "{\"status\":" + status + "}") .getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "application/json"); exchange.sendResponseHeaders(status, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }); server.start(); return server; }}
public class ApiErrorsDemo { private static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build(); private static String base;
/** Returns the body for 2xx; turns every other status into a meaningful exception. */ static String getProductJson(String id) throws IOException, InterruptedException { HttpRequest request = HttpRequest.newBuilder(URI.create(base + "/api/v1/products/" + id)) .timeout(Duration.ofSeconds(3)) .build(); HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); int status = response.statusCode(); if (status >= 200 && status < 300) { return response.body(); } if (status == 404) { throw new NotFoundException("Product " + id); } if (status >= 500) { throw new ServerErrorException("GET", request.uri(), status); } throw new ApiException("GET " + request.uri().getPath() + " was rejected with " + status + ": " + response.body(), status); }
public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = ProductApi.start(); base = "http://127.0.0.1:" + server.getAddress().getPort(); try { for (String id : new String[] {"1", "99", "5", "abc"}) { try { System.out.println("OK " + getProductJson(id)); } catch (NotFoundException e) { System.out.println("MISSING " + e.getMessage()); } catch (ServerErrorException e) { System.out.println("RETRY? " + e.getMessage()); } catch (ApiException e) { System.out.println("BUG? " + e.getMessage()); } } } finally { server.stop(0); } }}OK {"id":1,"name":"Redmi Note 13 5G"}
MISSING Product 99 not found
RETRY? GET /api/v1/products/5 failed on the server with 503
BUG? GET /api/v1/products/abc was rejected with 400: {"status":400}What this code does
getProductJsonreturns the body only for 2xx. Every other status becomes an exception whose type says what happened:NotFoundException,ServerErrorExceptionor the generalApiException.- Because
NotFoundExceptionandServerErrorExceptionextendApiException, the caller catches the specific ones first and the general one last, just likecatchblocks for any exception family. - Each call has a connect timeout on the client and a request timeout on the request, the habit from the first section.
The method returns data only for 2xx. The code that calls getProduct(9) then thinks in shop terms, "the product is missing" or "the server is down, try later", not in numbers. One catch (NotFoundException e) is clearer than an if on 404 in every screen, and the checks live in one place instead of being copied everywhere.
Keep these exceptions unchecked (extend RuntimeException), put the method, path and status in the message, and never put passwords, tokens or full request bodies in it, because messages end up in logs.
Next step
Check your understanding
12 quick questions