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.httpHttpURLConnection
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.HttpClient is an immutable description of one request, built with a builder: URI, method, headers, body publisher and timeout.HttpRequest carries the status, headers and a body of typeHttpResponse<T> . The type is chosen by theT you pass toBodyHandler : asend , a file, a stream of lines and so on.String
Underneath, the client is non-blocking. One selector thread handles all connections, and bodies flow through the reactive Flowsendhttp://https://
| Feature | HttpURLConnection | HttpClient |
|---|---|---|
| HTTP/2 | No | Yes; HTTP/3 as an opt-in in JDK 26 (JEP 517) |
| Asynchronous requests | No | sendAsyncCompletableFuture |
| Body handling | Raw streams | Handlers: string, file, lines, stream, custom |
| Error statuses | getInputStream | Normal responses; you check the status |
| Immutability and thread safety | One mutable object per request | Shared client, immutable requests |
AutoCloseable | No (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
returns a greeting, and/hello redirects to it;/old reports the size and type of the request body;/echo lists the request headers it received;/headers answers after 300 ms,/item?id=N after N ms, and/delay?ms=N after 3 seconds;/slow returns 1,000 log lines;/lines returns a 503 with a large HTML page;/unavailable- anything else returns a 404.
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.
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:
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
read the body as aBodyHandlers.ofString() , using the charset from theString header, or UTF-8 if none is given. The response wasContent-Type because the JDK test server does not speak HTTP/2; the client fell back without any error.HTTP_1_1- The JSON body
is 23 characters, and the server saw the{"name":"Ana","age":30} header the request set.Content-Type has no JSON support of its own; use a library such asHttpClientJackson to build and parse the strings. - A 404 is returned as a normal response.
throws only for transport problems such as connection failures and timeouts, so always checkHttpClient .statusCode() - The default client returned the 301 instead of following it. With
it followed the redirect, except from HTTPS to HTTP, andRedirect.NORMAL showed the final addressr.uri() ./hello on the request limits how long to wait for the response: the 3-second endpoint failed after 500 ms withtimeout .HttpTimeoutException on the client limits only connection setup. Without either, a request to a server that never answers waits forever.connectTimeout
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.
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):
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
rejected the raw space withURI.create .IllegalArgumentException turned "Zürich & Co" intoURLEncoder.encode : the two UTF-8 bytes ofZ%C3%BCrich+%26+Co asü , the ampersand as%C3%BC so it is not read as a parameter separator, and the spaces as%26 . Encode each value separately, never the whole URL.+- Besides the two headers the program set, the client added
, aHost ofUser-Agent , andJava-http-client/21 withConnection: Upgrade, HTTP2-Settings . 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.Upgrade: h2c - Header names arrived as
andX-request-id : the JDK server normalizes the case. HTTP header names are case-insensitive, so code must not rely on their spelling.User-agent ,Host andConnection are restricted: the client sets them itself, andContent-Length threwheader() . The system propertyIllegalArgumentException lifts the restriction for some of them when a test really needs it.jdk.httpclient.allowRestrictedHeaders- A built
cannot be changed.HttpRequest (Java 16) copies it, here leaving out the oldHttpRequest.newBuilder(original, filter) header so the copy could set a new value.X-Trace
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
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:
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)
returned a lazyofLines() , 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.Stream<String> wrote the 13,903 bytes straight to disk, so a download of any size needs no more memory than a small buffer.ofFile(path) 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.ofInputStream() kept the status and headers and threw the body away, here 13,903 bytes according todiscarding() .Content-Length- A
is a function from the status and headers to aBodyHandler , so it can choose per response. For the 503, it replaced the large HTML page with a short note instead of reading it into aBodySubscriber .String
Uploads use the matching BodyPublishersofStringofByteArrayofFileofInputStreamnoBody()
Asynchronous requests and their errors
sendAsyncCompletableFutureallOf
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:
{"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
, but whensendAsync was called, wrapped in ajoin() whose cause was theCompletionException . UnwrapConnectException before deciding what went wrong.getCause() 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.handle andexceptionally work the same way.whenComplete
Many requests: sequential, sendAsync or virtual threads
Since Java 21 there is a second way to run requests in parallel: plain blocking send
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):
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.
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.sendAsync- The two parallel styles were close. Virtual threads let you write ordinary, sequential-looking code with normal exceptions;
fits code that already composessendAsync s. SeeCompletableFuturevirtual threads .
Firing hundreds of parallel requests at one server can overload it. Limit concurrency with a
Which approach to use
| Need | Use |
|---|---|
| One client for the whole application | HttpClient.newBuilder()...build() |
| Small text or JSON responses | BodyHandlers.ofString() |
| Downloads | BodyHandlers.ofFile(path) |
| Large line-based responses | BodyHandlers.ofLines() |
| Only the status | BodyHandlers.discarding() |
| Query parameters | URLEncoder.encode(value, UTF_8) |
| Never hang | connectTimeouttimeout |
| Follow redirects | followRedirects(Redirect.NORMAL) |
| Many requests at once | Virtual threads with sendsendAsync |
| Error statuses | Check statusCode() |