Java HttpClient

java.net.http.HttpClient, standard since Java 11, sends HTTP/1.1 and HTTP/2 requests synchronously or asynchronously without any library. This page explains how its three types fit together, then runs every common task against a small server started on localhost: headers and query encoding, streaming bodies to lines or files, errors and redirects, timeouts, and many requests at once with sendAsync or virtual threads.

Contents

How HttpClient works

The java.net.http API was an incubator module in Java 9 (JEP 110) and became standard in Java 11 (JEP 321), replacing the old HttpURLConnection for new code. It is built from three types:

  • HttpClient holds the settings (redirect policy, timeouts, proxy, TLS) and a pool of connections. It is thread-safe and meant to be created once and shared; creating one per request throws away the connection pool.
  • HttpRequest is an immutable description of one request, built with a builder: URI, method, headers, body publisher and timeout.
  • HttpResponse<T> carries the status, headers and a body of type T. The type is chosen by the BodyHandler you pass to send: a String, a file, a stream of lines and so on.

Underneath, the client is non-blocking. One selector thread handles all connections, and bodies flow through the reactive Flow API in chunks, which is why a body can go straight to a file without being held in memory. send uses the same asynchronous machinery and waits for its result. For http:// URLs the client prefers HTTP/2 and asks the server to upgrade; if the server does not, it stays on HTTP/1.1. For https:// it negotiates the version during the TLS handshake.

HttpClient compared with HttpURLConnection
FeatureHttpURLConnection (Java 1.1)HttpClient (Java 11)
HTTP/2NoYes; HTTP/3 as an opt-in in JDK 26 (JEP 517)
Asynchronous requestsNosendAsync returning a CompletableFuture
Body handlingRaw streamsHandlers: string, file, lines, stream, custom
Error statusesgetInputStream throws for 4xx and 5xxNormal responses; you check the status
Immutability and thread safetyOne mutable object per requestShared client, immutable requests
AutoCloseableNo (disconnect)Since Java 21

To make the examples runnable anywhere, including without internet access, a helper starts the JDK's built-in com.sun.net.httpserver.HttpServer on a free local port. All programs were compiled and run on JDK 21. The server's endpoints:

  • /hello returns a greeting, and /old redirects to it;
  • /echo reports the size and type of the request body;
  • /headers lists the request headers it received;
  • /item?id=N answers after 300 ms, /delay?ms=N after N ms, and /slow after 3 seconds;
  • /lines returns 1,000 log lines;
  • /unavailable returns a 503 with a large HTML page;
  • anything else returns a 404.
Java
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;

// A tiny HTTP server on localhost so the examples run without internet access
final class LocalServer {
    private LocalServer() {
    }

    static HttpServer start() throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
        server.createContext("/hello", ex -> reply(ex, 200, "text/plain", "Hello, HttpClient"));
        server.createContext("/echo", ex -> {
            String body = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
            String type = ex.getRequestHeaders().getFirst("Content-Type");
            reply(ex, 201, "application/json",
                    "{\"received\":" + body.length() + ",\"type\":\"" + type + "\"}");
        });
        server.createContext("/item", ex -> {
            sleep(300);
            String id = ex.getRequestURI().getQuery().replace("id=", "");
            reply(ex, 200, "application/json", "{\"id\":" + id + ",\"price\":" + id + "0}");
        });
        server.createContext("/slow", ex -> {
            sleep(3000);
            reply(ex, 200, "text/plain", "finally");
        });
        server.createContext("/old", ex -> {
            ex.getResponseHeaders().add("Location", "/hello");
            ex.sendResponseHeaders(301, -1);
            ex.close();
        });
        server.createContext("/headers", ex -> {
            StringBuilder sb = new StringBuilder();
            new java.util.TreeMap<>(ex.getRequestHeaders()).forEach((k, v) -> sb.append(k)
                    .append(": ").append(String.join(",", v)).append('\n'));
            sb.append("query: ").append(ex.getRequestURI().getRawQuery());
            reply(ex, 200, "text/plain", sb.toString());
        });
        server.createContext("/delay", ex -> {
            sleep(Long.parseLong(ex.getRequestURI().getQuery().replace("ms=", "")));
            reply(ex, 200, "text/plain", "done");
        });
        server.createContext("/lines", ex -> {
            StringBuilder sb = new StringBuilder();
            for (int i = 1; i <= 1000; i++) {
                sb.append(i % 100 == 0 ? "ERROR " : "INFO ").append("line ").append(i)
                        .append('\n');
            }
            reply(ex, 200, "text/plain; charset=utf-8", sb.toString());
        });
        server.createContext("/unavailable", ex -> reply(ex, 503, "text/html",
                "<html>" + "maintenance page ".repeat(500) + "</html>"));
        server.createContext("/", ex -> reply(ex, 404, "text/plain", "no such page"));
        server.start();
        return server;
    }

    static void reply(HttpExchange ex, int status, String type, String body) throws IOException {
        byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
        ex.getResponseHeaders().add("Content-Type", type);
        ex.sendResponseHeaders(status, bytes.length);
        try (OutputStream out = ex.getResponseBody()) {
            out.write(bytes);
        }
    }

    static void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

Synchronous requests: GET, POST, errors, redirects and timeouts

The program sends one request of each common kind: a GET, a JSON POST, a request for a missing page, a redirect, and a request that is too slow.

Java
import com.sun.net.httpserver.HttpServer;
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;

public class SyncRequests {

    public static void main(String[] args) throws Exception {
        HttpServer server = LocalServer.start();
        String base = "http://127.0.0.1:" + server.getAddress().getPort();

        try (HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(5))
                .build()) {

            // GET: the body handler decides how the response body is read
            HttpRequest get = HttpRequest.newBuilder(URI.create(base + "/hello")).build();
            HttpResponse<String> r = client.send(get, HttpResponse.BodyHandlers.ofString());
            System.out.println("GET /hello -> " + r.statusCode() + " " + r.version() + ", type "
                    + r.headers().firstValue("content-type").orElse("?") + ", body: " + r.body());

            // POST with a JSON body
            HttpRequest post = HttpRequest.newBuilder(URI.create(base + "/echo"))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString("{\"name\":\"Ana\",\"age\":30}"))
                    .build();
            HttpResponse<String> p = client.send(post, HttpResponse.BodyHandlers.ofString());
            System.out.println("POST /echo -> " + p.statusCode() + ", body: " + p.body());

            // Error statuses are normal responses, not exceptions
            HttpResponse<String> missing = client.send(
                    HttpRequest.newBuilder(URI.create(base + "/nothing")).build(),
                    HttpResponse.BodyHandlers.ofString());
            System.out.println("GET /nothing -> " + missing.statusCode() + ", body: "
                    + missing.body());

            // Redirects are NOT followed by default
            HttpRequest old = HttpRequest.newBuilder(URI.create(base + "/old")).build();
            System.out.println("GET /old, default client -> "
                    + client.send(old, HttpResponse.BodyHandlers.ofString()).statusCode());

            // Per-request timeout
            HttpRequest slow = HttpRequest.newBuilder(URI.create(base + "/slow"))
                    .timeout(Duration.ofMillis(500)).build();
            try {
                client.send(slow, HttpResponse.BodyHandlers.ofString());
            } catch (HttpTimeoutException e) {
                System.out.println("GET /slow with 500 ms timeout -> HttpTimeoutException");
            }
        }

        try (HttpClient following = HttpClient.newBuilder()
                .followRedirects(HttpClient.Redirect.NORMAL).build()) {
            HttpResponse<String> r = following.send(
                    HttpRequest.newBuilder(URI.create(base + "/old")).build(),
                    HttpResponse.BodyHandlers.ofString());
            System.out.println("GET /old, Redirect.NORMAL -> " + r.statusCode() + " from "
                    + r.uri().getPath() + ", body: " + r.body());
        }
        server.stop(0);
    }
}

Output:

Output
GET /hello -> 200 HTTP_1_1, type text/plain, body: Hello, HttpClient
POST /echo -> 201, body: {"received":23,"type":"application/json"}
GET /nothing -> 404, body: no such page
GET /old, default client -> 301
GET /slow with 500 ms timeout -> HttpTimeoutException
GET /old, Redirect.NORMAL -> 200 from /hello, body: Hello, HttpClient
  • BodyHandlers.ofString() read the body as a String, using the charset from the Content-Type header, or UTF-8 if none is given. The response was HTTP_1_1 because the JDK test server does not speak HTTP/2; the client fell back without any error.
  • The JSON body {"name":"Ana","age":30} is 23 characters, and the server saw the Content-Type header the request set. HttpClient has no JSON support of its own; use a library such as Jackson to build and parse the strings.
  • A 404 is returned as a normal response. HttpClient throws only for transport problems such as connection failures and timeouts, so always check statusCode().
  • The default client returned the 301 instead of following it. With Redirect.NORMAL it followed the redirect, except from HTTPS to HTTP, and r.uri() showed the final address /hello.
  • timeout on the request limits how long to wait for the response: the 3-second endpoint failed after 500 ms with HttpTimeoutException. connectTimeout on the client limits only connection setup. Without either, a request to a server that never answers waits forever.

Headers, query strings and immutable requests

The program sends a search term with a space, an accent and an ampersand in the query string, and asks the server to list the headers it received. It then tries to set headers the client controls, and copies a request with one header changed.

Java
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

public class RequestDetails {

    public static void main(String[] args) throws Exception {
        HttpServer server = LocalServer.start();
        String base = "http://127.0.0.1:" + server.getAddress().getPort();

        try (HttpClient client = HttpClient.newHttpClient()) {
            // Query values must be encoded; URI.create rejects a raw space
            String search = "Zürich & Co";
            try {
                URI.create(base + "/headers?q=" + search);
            } catch (IllegalArgumentException e) {
                System.out.println("raw space in URI: IllegalArgumentException");
            }
            String q = URLEncoder.encode(search, StandardCharsets.UTF_8);
            System.out.println("URLEncoder.encode: " + q);

            HttpRequest req = HttpRequest.newBuilder(URI.create(base + "/headers?q=" + q))
                    .header("Accept", "text/plain")
                    .header("X-Request-Id", "42")
                    .build();
            String seen = client.send(req, HttpResponse.BodyHandlers.ofString()).body();
            System.out.println("--- what the server received ---");
            // The client version and the port change between runs, so mask them
            seen.lines().map(l -> l.replaceAll("(Java-http-client/\\d+)\\S*", "$1")
                    .replaceAll("127\\.0\\.0\\.1:\\d+", "127.0.0.1:<port>"))
                    .forEach(System.out::println);
        }

        // Some headers are controlled by the client and cannot be set
        for (String name : new String[] {"Host", "Connection", "Content-Length"}) {
            try {
                HttpRequest.newBuilder(URI.create(base + "/")).header(name, "x");
                System.out.println(name + ": accepted");
            } catch (IllegalArgumentException e) {
                System.out.println(name + ": IllegalArgumentException (" + e.getMessage() + ")");
            }
        }

        // A request is immutable; copy it to change one thing
        HttpRequest original = HttpRequest.newBuilder(URI.create(base + "/hello"))
                .header("X-Trace", "a").build();
        HttpRequest copy = HttpRequest.newBuilder(original, (n, v) -> !n.equals("X-Trace"))
                .header("X-Trace", "b").build();
        System.out.println("original X-Trace " + original.headers().firstValue("X-Trace")
                .orElseThrow() + ", copy X-Trace " + copy.headers().firstValue("X-Trace")
                .orElseThrow() + ", method " + copy.method());
        server.stop(0);
    }
}

Output (the port and the JDK update number are masked, because they change between runs):

Output
raw space in URI: IllegalArgumentException
URLEncoder.encode: Z%C3%BCrich+%26+Co
--- what the server received ---
Accept: text/plain
Connection: Upgrade, HTTP2-Settings
Host: 127.0.0.1:<port>
Http2-settings: AAEAAEAAAAIAAAAAAAMAAAAAAAQBAAAAAAUAAEAAAAYABgAA
Upgrade: h2c
User-agent: Java-http-client/21
X-request-id: 42
query: q=Z%C3%BCrich+%26+Co
Host: IllegalArgumentException (restricted header name: "Host")
Connection: IllegalArgumentException (restricted header name: "Connection")
Content-Length: IllegalArgumentException (restricted header name: "Content-Length")
original X-Trace a, copy X-Trace b, method GET
  • URI.create rejected the raw space with IllegalArgumentException. URLEncoder.encode turned "Zürich & Co" into Z%C3%BCrich+%26+Co: the two UTF-8 bytes of ü as %C3%BC, the ampersand as %26 so it is not read as a parameter separator, and the spaces as +. Encode each value separately, never the whole URL.
  • Besides the two headers the program set, the client added Host, a User-Agent of Java-http-client/21, and Connection: Upgrade, HTTP2-Settings with Upgrade: h2c. That last pair is the HTTP/2 upgrade attempt over plain HTTP. The server ignored it, which is why the response was HTTP/1.1.
  • Header names arrived as X-request-id and User-agent: the JDK server normalizes the case. HTTP header names are case-insensitive, so code must not rely on their spelling.
  • Host, Connection and Content-Length are restricted: the client sets them itself, and header() threw IllegalArgumentException. The system property jdk.httpclient.allowRestrictedHeaders lifts the restriction for some of them when a test really needs it.
  • A built HttpRequest cannot be changed. HttpRequest.newBuilder(original, filter) (Java 16) copies it, here leaving out the old X-Trace header so the copy could set a new value.

Body handlers: strings, lines, files and streams

The body handler decides how the response body is consumed. The program fetches the 1,000-line log several ways, and finally uses a custom handler that keeps the body only for successful responses, against /hello and the 503 page.

Java
import com.sun.net.httpserver.HttpServer;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandler;
import java.net.http.HttpResponse.BodyHandlers;
import java.net.http.HttpResponse.BodySubscribers;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

public class BodyHandlersDemo {

    public static void main(String[] args) throws Exception {
        HttpServer server = LocalServer.start();
        String base = "http://127.0.0.1:" + server.getAddress().getPort();
        try (HttpClient client = HttpClient.newHttpClient()) {
            HttpRequest lines = HttpRequest.newBuilder(URI.create(base + "/lines")).build();

            // ofLines: a lazy Stream<String>, read as the body arrives
            HttpResponse<Stream<String>> streamed = client.send(lines, BodyHandlers.ofLines());
            try (Stream<String> body = streamed.body()) {
                System.out.println("ofLines: ERROR lines = "
                        + body.filter(l -> l.startsWith("ERROR")).count());
            }

            // ofFile: straight to disk, never held in memory as a whole
            Path target = Files.createTempFile("download", ".txt");
            HttpResponse<Path> saved = client.send(lines, BodyHandlers.ofFile(target));
            System.out.println("ofFile: " + Files.size(saved.body()) + " bytes written");
            Files.delete(target);

            // ofInputStream: read it yourself; close it, or the connection is not reused
            HttpResponse<InputStream> raw = client.send(lines, BodyHandlers.ofInputStream());
            try (InputStream in = raw.body()) {
                System.out.println("ofInputStream: first bytes \"" + new String(
                        in.readNBytes(11), StandardCharsets.UTF_8) + "\"");
            }

            // discarding: status and headers only
            HttpResponse<Void> head = client.send(lines, BodyHandlers.discarding());
            System.out.println("discarding: status " + head.statusCode() + ", length header "
                    + head.headers().firstValueAsLong("content-length").orElse(-1));

            // A handler that decides by status: keep the body only for 2xx answers
            BodyHandler<String> okOnly = info -> info.statusCode() / 100 == 2
                    ? BodySubscribers.ofString(StandardCharsets.UTF_8)
                    : BodySubscribers.replacing("(body of a " + info.statusCode()
                            + " response dropped)");
            for (String path : new String[] {"/hello", "/unavailable"}) {
                HttpResponse<String> r = client.send(
                        HttpRequest.newBuilder(URI.create(base + path)).build(), okOnly);
                System.out.println(path + " -> " + r.statusCode() + ": " + r.body());
            }
        }
        server.stop(0);
    }
}

Output:

Output
ofLines: ERROR lines = 10
ofFile: 13903 bytes written
ofInputStream: first bytes "INFO line 1"
discarding: status 200, length header 13903
/hello -> 200: Hello, HttpClient
/unavailable -> 503: (body of a 503 response dropped)
  • ofLines() returned a lazy Stream<String>, and the filter counted 10 ERROR lines, one every 100 lines, while the body was still arriving. Close the stream, as the try-with-resources does.
  • ofFile(path) wrote the 13,903 bytes straight to disk, so a download of any size needs no more memory than a small buffer.
  • ofInputStream() hands you the raw stream. The program read only the first 11 bytes; closing the stream early releases the connection, while forgetting to close it keeps the connection busy.
  • discarding() kept the status and headers and threw the body away, here 13,903 bytes according to Content-Length.
  • A BodyHandler is a function from the status and headers to a BodySubscriber, so it can choose per response. For the 503, it replaced the large HTML page with a short note instead of reading it into a String.

Uploads use the matching BodyPublishers: ofString, ofByteArray, ofFile to stream a file, ofInputStream, and noBody() for methods such as DELETE.

Asynchronous requests and their errors

sendAsync returns a CompletableFuture immediately, so many requests can be in flight at once from one thread. The program starts five requests to the 300 ms endpoint, waits for all of them with allOf, and then shows what failures look like: a connection to a closed port, and a timeout handled without try and catch.

Java
import com.sun.net.httpserver.HttpServer;
import java.net.ConnectException;
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;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.stream.IntStream;

public class AsyncRequests {

    public static void main(String[] args) throws Exception {
        HttpServer server = LocalServer.start();
        String base = "http://127.0.0.1:" + server.getAddress().getPort();

        try (HttpClient client = HttpClient.newHttpClient()) {
            long start = System.nanoTime();

            // Start five requests at once; each takes about 300 ms on the server
            List<CompletableFuture<String>> futures = IntStream.rangeClosed(1, 5)
                    .mapToObj(id -> HttpRequest.newBuilder(URI.create(base + "/item?id=" + id))
                            .build())
                    .map(req -> client.sendAsync(req, HttpResponse.BodyHandlers.ofString())
                            .thenApply(HttpResponse::body))
                    .toList();

            CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join();
            long ms = (System.nanoTime() - start) / 1000000;

            futures.forEach(f -> System.out.println(f.join()));
            System.out.println("5 requests of ~300 ms each finished in under 1,000 ms: "
                    + (ms < 1000));

            // Failures arrive inside the future, wrapped in CompletionException
            HttpRequest closedPort = HttpRequest.newBuilder(URI.create("http://127.0.0.1:1/"))
                    .build();
            try {
                client.sendAsync(closedPort, HttpResponse.BodyHandlers.ofString()).join();
            } catch (CompletionException e) {
                System.out.println("join() threw CompletionException, cause: "
                        + e.getCause().getClass().getSimpleName()
                        + (e.getCause() instanceof ConnectException ? " (connection refused)"
                        : ""));
            }

            // handle() turns success and failure into one value, without try/catch
            HttpRequest slow = HttpRequest.newBuilder(URI.create(base + "/slow"))
                    .timeout(Duration.ofMillis(300)).build();
            String outcome = client.sendAsync(slow, HttpResponse.BodyHandlers.ofString())
                    .handle((r, ex) -> ex == null ? "status " + r.statusCode()
                            : ex.getCause() instanceof HttpTimeoutException
                            ? "timed out, using a cached value" : "failed: " + ex)
                    .join();
            System.out.println("slow request: " + outcome);
        }
        server.stop(0);
    }
}

Output:

Output
{"id":1,"price":10}
{"id":2,"price":20}
{"id":3,"price":30}
{"id":4,"price":40}
{"id":5,"price":50}
5 requests of ~300 ms each finished in under 1,000 ms: true
join() threw CompletionException, cause: ConnectException (connection refused)
slow request: timed out, using a cached value
  • All five ran at the same time, so the total was close to one request's 300 ms instead of 1.5 seconds. The results are printed in the order the futures were created, not the order they finished.
  • Port 1 refused the connection. The failure did not appear at sendAsync, but when join() was called, wrapped in a CompletionException whose cause was the ConnectException. Unwrap getCause() before deciding what went wrong.
  • handle received either the response or the exception and turned both into one value: the slow request timed out after 300 ms, and the program fell back to a cached answer. exceptionally and whenComplete work the same way.

Many requests: sequential, sendAsync or virtual threads

Since Java 21 there is a second way to run requests in parallel: plain blocking send calls, each on its own virtual thread. The program sends 20 requests to an endpoint that takes 100 ms, three ways, with one shared client.

Java
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ConcurrencyCompare {

    static final int REQUESTS = 20;

    public static void main(String[] args) throws Exception {
        HttpServer server = LocalServer.start();
        URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort()
                + "/delay?ms=100");
        HttpRequest req = HttpRequest.newBuilder(uri).build();

        try (HttpClient client = HttpClient.newHttpClient()) {
            client.send(req, HttpResponse.BodyHandlers.discarding());     // warm-up

            long start = System.nanoTime();
            for (int i = 0; i < REQUESTS; i++) {
                client.send(req, HttpResponse.BodyHandlers.ofString());
            }
            report("sequential send()", start);

            start = System.nanoTime();
            List<CompletableFuture<HttpResponse<String>>> futures = new ArrayList<>();
            for (int i = 0; i < REQUESTS; i++) {
                futures.add(client.sendAsync(req, HttpResponse.BodyHandlers.ofString()));
            }
            futures.forEach(CompletableFuture::join);
            report("sendAsync + join", start);

            start = System.nanoTime();
            try (ExecutorService vt = Executors.newVirtualThreadPerTaskExecutor()) {
                List<Future<HttpResponse<String>>> results = new ArrayList<>();
                for (int i = 0; i < REQUESTS; i++) {
                    results.add(vt.submit(() -> client.send(req,
                            HttpResponse.BodyHandlers.ofString())));
                }
                for (Future<HttpResponse<String>> f : results) {
                    f.get();
                }
            }
            report("send() on virtual threads", start);
        }
        server.stop(0);
    }

    static void report(String label, long start) {
        long ms = (System.nanoTime() - start) / 1000000;
        System.out.printf("%-28s %d requests of 100 ms: %5d ms%n", label, REQUESTS, ms);
    }
}

Output (rough comparison on a 2-CPU Linux VM, JDK 21; one run each, after a warm-up request):

Output
sequential send()            20 requests of 100 ms:  2949 ms
sendAsync + join             20 requests of 100 ms:   174 ms
send() on virtual threads    20 requests of 100 ms:   123 ms
  • Sequential requests added up: 20 requests took at least 20 times 100 ms, plus the overhead of each round trip.
  • sendAsync and virtual threads both took little more than one request's time, roughly twenty times faster than sequential. Both kept all 20 requests in flight at once; over HTTP/1.1 that means 20 connections to the server.
  • The two parallel styles were close. Virtual threads let you write ordinary, sequential-looking code with normal exceptions; sendAsync fits code that already composes CompletableFutures. See virtual threads.

Firing hundreds of parallel requests at one server can overload it. Limit concurrency with a Semaphore or a bounded executor. Connection reuse, authentication, cookies and retries are covered in the HttpClient deep dive.

Which approach to use

Choosing HttpClient features
NeedUse
One client for the whole applicationHttpClient.newBuilder()...build(), shared by all threads
Small text or JSON responsesBodyHandlers.ofString()
DownloadsBodyHandlers.ofFile(path)
Large line-based responsesBodyHandlers.ofLines() in try-with-resources
Only the statusBodyHandlers.discarding()
Query parametersURLEncoder.encode(value, UTF_8) for each value
Never hangconnectTimeout on the client and timeout on each request
Follow redirectsfollowRedirects(Redirect.NORMAL)
Many requests at onceVirtual threads with send, or sendAsync, with a concurrency limit
Error statusesCheck statusCode(); only transport failures throw