Java 17: Call a REST API with the Java 11 HttpClient. Compare HttpURLConnection, sync, async and retrying clients.
Problem
Call GET /rates/{currency} on a partner service with a timeout, handle errors, call several currencies concurrently, and retry transient failures. The demo starts a local JDK HttpServer, so it runs offline.
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;
final class FakeRatesServer implements AutoCloseable {
final HttpServer server;
final AtomicInteger flakyCalls = new AtomicInteger();
FakeRatesServer() throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/rates/", ex -> {
String cur = ex.getRequestURI().getPath().substring("/rates/".length());
boolean fail = cur.equals("FLAKY") && flakyCalls.incrementAndGet() < 3; // fails twice, then works
byte[] body = (fail ? "{\"error\":\"busy\"}" : "{\"currency\":\"" + cur + "\",\"rate\":83.2}").getBytes(StandardCharsets.UTF_8);
ex.sendResponseHeaders(fail ? 503 : 200, body.length);
ex.getResponseBody().write(body);
ex.close();
});
server.start();
}
String base() { return "http://127.0.0.1:" + server.getAddress().getPort(); }
@Override public void close() { server.stop(0); }
}Approach 1: HttpURLConnection (legacy, pre-Java 11)
Verbose, blocking, manual stream handling, and HTTP/1.1 only.
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
class RatesLegacy {
static String get(String base, String currency) throws Exception {
HttpURLConnection conn = (HttpURLConnection) URI.create(base + "/rates/" + currency).toURL().openConnection();
conn.setConnectTimeout(2000);
conn.setReadTimeout(2000);
try {
if (conn.getResponseCode() != 200) throw new IllegalStateException("HTTP " + conn.getResponseCode());
try (InputStream in = conn.getInputStream()) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
} finally {
conn.disconnect();
}
}
}Approach 2: HttpClient, synchronous (Java 11)
Immutable, thread-safe client to reuse across calls (it pools connections and supports HTTP/2); builder-style requests; typed body handlers.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
class RatesSync {
static final HttpClient CLIENT = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2))
.version(HttpClient.Version.HTTP_1_1)
.build();
static HttpRequest request(String base, String currency) {
return HttpRequest.newBuilder(URI.create(base + "/rates/" + currency))
.timeout(Duration.ofSeconds(2)) // per-request response timeout
.header("Accept", "application/json")
.GET().build();
}
static String get(String base, String currency) throws Exception {
HttpResponse<String> res = CLIENT.send(request(base, currency), HttpResponse.BodyHandlers.ofString());
if (res.statusCode() != 200) throw new IllegalStateException("HTTP " + res.statusCode());
return res.body();
}
}Approach 3: HttpClient, asynchronous fan-out
sendAsync returns a CompletableFuture, so several calls run concurrently without blocking threads.
import java.net.http.HttpResponse;
import java.util.List;
import java.util.concurrent.CompletableFuture;
class RatesAsync {
static List<String> getAll(String base, List<String> currencies) {
List<CompletableFuture<String>> futures = currencies.stream()
.map(c -> RatesSync.CLIENT.sendAsync(RatesSync.request(base, c), HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body))
.toList();
return futures.stream().map(CompletableFuture::join).toList();
}
}Approach 4: Retry with exponential backoff for transient errors
Retry only idempotent requests and only for transient failures (503, 429, connection errors), with a small cap and growing delays. In Spring applications you would use Resilience4j or Spring Retry rather than hand-rolling this.
import java.net.http.HttpResponse;
import java.util.Set;
class RatesRetry {
private static final Set<Integer> TRANSIENT = Set.of(429, 502, 503, 504);
static String get(String base, String currency, int maxAttempts) throws Exception {
long backoffMs = 50;
for (int attempt = 1; ; attempt++) {
HttpResponse<String> res = RatesSync.CLIENT.send(RatesSync.request(base, currency), HttpResponse.BodyHandlers.ofString());
if (res.statusCode() == 200) return res.body();
if (!TRANSIENT.contains(res.statusCode()) || attempt == maxAttempts)
throw new IllegalStateException("HTTP " + res.statusCode() + " after " + attempt + " attempt(s)");
Thread.sleep(backoffMs + java.util.concurrent.ThreadLocalRandom.current().nextLong(backoffMs)); // jitter
backoffMs *= 2;
}
}
}
class RatesDemo {
public static void main(String[] args) throws Exception {
try (FakeRatesServer server = new FakeRatesServer()) {
String base = server.base();
System.out.println(RatesLegacy.get(base, "USD"));
System.out.println(RatesSync.get(base, "EUR"));
System.out.println(RatesAsync.getAll(base, java.util.List.of("GBP", "JPY", "AED")));
System.out.println(RatesRetry.get(base, "FLAKY", 4) + " after " + server.flakyCalls.get() + " calls"); // succeeds on the 3rd
}
}
}Feasible → optimal
HttpURLConnection is feasible but verbose and blocking. A shared HttpClient is the modern JDK default; sendAsync (or, on Java 21, plain send on virtual threads) gives concurrency; production code adds timeouts, bounded retries with backoff and jitter, and circuit breaking. In Spring Boot 3.2+, RestClient (or declarative HTTP interfaces) wraps this with message conversion and observability.
Follow-up questions interviewers ask
Try answering each one before you open it.
Why should the HttpClient be created once and reused?
It owns a connection pool, an executor and TLS session caches. Creating one per request throws all that away, forcing new TCP and TLS handshakes every time (tens of milliseconds) and leaking threads until garbage collection. HttpClient is immutable and thread-safe, so a single shared instance (a Spring bean) is correct.
What timeouts do you need for an outbound HTTP call?
A connect timeout (time to establish TCP and TLS), a response or read timeout (time waiting for the server), and often an overall deadline for the operation including retries, so a request never waits longer than its own caller's budget. Missing timeouts are the most common cause of thread and connection pool exhaustion in production.