Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Use java.net.http.HttpClient to send a GET request with a 5 second timeout and parse the body as a String. Show both the synchronous and asynchronous call.

We build one client with HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build() and a request with HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(5)).GET().build(). The synchronous call is client.send(request, HttpResponse.BodyHandlers.ofString()), which blocks and returns an HttpResponse<String>; the asynchronous call is client.sendAsync(request, BodyHandlers.ofString()), which returns a CompletableFuture<HttpResponse<String>> at once. The client holds a connection pool and is thread-safe, so we create it once and reuse it.

Why this question is asked

Since Java 11, the JDK has a modern HTTP client in java.net.http that supports HTTP/1.1 and HTTP/2, synchronous and asynchronous calls, and needs no extra dependency. It replaced the old HttpURLConnection for most new code, and it is a common choice for small services, command-line tools and tests. Interviewers ask for this snippet to see whether we know the builder API, where the two timeouts go and what each one covers, and how to handle errors in both styles. In this answer, we will build the client and the request, make the synchronous call, make the asynchronous call, handle timeouts and errors, and see why the client should be shared.

1A Quick Recap of the Three Types

The API has three main types. HttpClient holds configuration such as timeouts, redirects and the HTTP version, and owns the connection pool and its threads. HttpRequest describes one request: URI, method, headers, body and its own timeout. HttpResponse<T> is the result, with the status code, headers and a body of type T. The body type is chosen by a BodyHandler, which decides how the response bytes are turned into a value; BodyHandlers.ofString() collects them into a String using the charset from the response headers, UTF-8 by default.

Both HttpClient and HttpRequest are immutable once built, so they are safe to share between threads.

2Building the Client and the Request

The two timeouts go in different places, and they cover different things.

Java
private static final HttpClient CLIENT = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5)) // limit for establishing the connection
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.example.com/items/42"))
.timeout(Duration.ofSeconds(5)) // limit for getting the response
.header("Accept", "application/json")
.GET() // the default method, written for clarity
.build();

connectTimeout on the client limits how long we wait to establish a connection to the server. timeout on the request limits how long we wait for the response once the request is sent. Without the request timeout, a call to a server that accepts the connection but never answers could wait forever, which is the classic way a slow dependency freezes a whole service.

3The Synchronous Call

send() blocks the calling thread until the response arrives, then returns it. It declares two checked exceptions: IOException for network failures, including timeouts, and InterruptedException if the waiting thread is interrupted.

Java
try {
HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode()); // 200
System.out.println(response.body()); // {"id":42,"name":"lamp"}
if (response.statusCode() >= 400) { // the client does not throw for error statuses
throw new IllegalStateException("HTTP " + response.statusCode());
}
} catch (HttpConnectTimeoutException e) { // could not connect within 5 s
log.warn("connect timeout", e);
} catch (HttpTimeoutException e) { // connected, but no response within 5 s
log.warn("request timeout", e);
} catch (IOException e) { // other network failures
log.warn("call failed", e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // keep the interrupt flag for the caller
}

Notice the order of the catch blocks: HttpConnectTimeoutException is a subclass of HttpTimeoutException, which is a subclass of IOException, so the most specific comes first. Notice too that a 404 or 500 is not an exception; it is a normal response with that status code, and we must check it ourselves. On Java 21 and later, blocking send() is a good fit for virtual threads, which makes the simple synchronous style scale.

4The Asynchronous Call

sendAsync() returns immediately with a CompletableFuture that completes when the response arrives. We attach the next steps instead of waiting.

Java
CompletableFuture<String> body = CLIENT
.sendAsync(request, HttpResponse.BodyHandlers.ofString()) // returns at once
.thenApply(response -> {
if (response.statusCode() >= 400) throw new IllegalStateException("HTTP " + response.statusCode());
return response.body();
});
body.thenAccept(json -> System.out.println(json)) // {"id":42,"name":"lamp"}
.exceptionally(e -> { // e is a CompletionException wrapping the cause
log.warn("call failed", e.getCause());
return null;
});
// Several calls at once, then wait for all of them
List<CompletableFuture<String>> calls = urls.stream()
.map(u -> CLIENT.sendAsync(requestFor(u), BodyHandlers.ofString()).thenApply(HttpResponse::body))
.toList();
CompletableFuture.allOf(calls.toArray(CompletableFuture[]::new)).join();
Step throughsend() versus sendAsync()
Caller threadHttpClientServer
send(request): caller blocks
GET /items/42
200 + body
HttpResponse<String> returned
sendAsync(request)
CompletableFuture returned at once
GET /items/42
200 + body; the future completes

8 messages in order. Play them, or step through them one at a time.

The asynchronous style shines when we need several calls in parallel without a thread per call, as in the last example. Errors arrive through the future instead of a catch block; in exceptionally, the exception is usually a CompletionException, so we look at getCause() to find the HttpTimeoutException or other failure. The callbacks usually run on the client's executor threads, so they should not block.

5Why We Reuse One HttpClient

An HttpClient owns a pool of open connections and the threads that drive them. Reusing one client lets requests to the same server share connections through keep-alive, and with HTTP/2 many requests run over a single connection at once. Creating a client per request throws all of that away: each call pays for a new TCP connection and TLS handshake, which can cost tens of milliseconds, and leaves a closed connection behind in TIME_WAIT. HttpClient is thread-safe, so the usual pattern is one instance per application or per downstream service, created at startup, as a static field or a Spring bean. Since Java 21, HttpClient also implements AutoCloseable, so a client created for a limited scope can be closed with try-with-resources.

6Follow-up questions

What does HttpRequest.timeout cover that connectTimeout does not?

connectTimeout only covers establishing the connection. The request timeout covers the wait after that: sending the request and waiting for the server to answer, so it catches a server that accepts connections but responds slowly or never. Note that in current JDKs it is measured until the response headers arrive, so a body that streams very slowly may need its own limit, for example orTimeout on the CompletableFuture; check your version's documentation. A reused pooled connection skips the connect step entirely, so only the request timeout applies to it.

Why does a 500 response not throw an exception?

Because the HTTP exchange succeeded: the server answered with a valid response that happens to report an error. The client only throws for transport problems, such as failing to connect or timing out. Deciding which status codes are errors is the caller's job.

How do we read JSON with this client?

The JDK has no JSON parser, so we read the body as a String or InputStream and parse it with a library such as Jackson, or write a small BodyHandler that maps the bytes with an ObjectMapper. Frameworks such as Spring's RestClient do this mapping for us.

7Conclusion

In this answer, we built a shared HttpClient with a 5 second connectTimeout and a request with a 5 second request timeout, then called it synchronously with send(request, BodyHandlers.ofString()), handling HttpConnectTimeoutException, HttpTimeoutException and status codes ourselves, and asynchronously with sendAsync, which returns a CompletableFuture<HttpResponse<String>> whose errors arrive wrapped in CompletionException. We reuse one client because it holds a thread-safe connection pool.

What to say in the interviewAbout 80 seconds aloud

Open with

I would create one HttpClient with HttpClient.newBuilder, set connectTimeout to Duration.ofSeconds(5), and build it, keeping it as a shared field or bean because it holds a connection pool and is thread-safe.

Then, if they want more

Creating one per request would pay for a new connection and TLS handshake every time. Then the request: HttpRequest.newBuilder with URI.create of the URL, timeout of five seconds, GET, and build.

The two timeouts cover different things: connectTimeout is only for establishing the connection, and the request timeout limits the wait for the response after the request is sent, which catches a server that accepts connections but never answers.

For the synchronous call I use client.send with HttpResponse.BodyHandlers.ofString, which blocks and returns an HttpResponse of String, so I read statusCode and body. It throws IOException, with HttpConnectTimeoutException and HttpTimeoutException as specific subclasses for the two timeouts, and InterruptedException, where I restore the interrupt flag. It does not throw for a 404 or 500, so I check the status myself.

For the asynchronous call I use sendAsync with the same body handler, which returns a CompletableFuture of HttpResponse of String immediately, and I chain thenApply to get the body and exceptionally for failures, unwrapping the CompletionException. On Java 21 I would often just use send on virtual threads.

About this answer

Last updated
12 November 2026
Versions it names
Java 21, Java 11
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Use java.net.http.HttpClient to send a GET request with a 5 second timeout and parse the...": https://scrivio-interview-library.netlify.app/java/networking/cebf0c0bad/