The Java HttpClient: Requests, Responses, Body Publishers and Handlers
Use java.net.http.HttpClient for synchronous HTTP: building and closing clients, HttpRequest builders with methods, headers and timeouts, body publishers for strings, files, forms and multipart, body handlers for strings, lines, streams, files and size limits, headers, redirects and errors.
kvi5hnuCode Sprout team member8 min readOn this page
URLConnection was designed in the 1990s for many protocols, and its HTTP support shows its age: a fussy order of steps, mutable state, error streams, global settings. When HTTP/2 arrived, the JDK got a new client instead of another layer of patches. The java.net.http module (standard since Java 11) provides HttpClient, HttpRequest and HttpResponse. It supports HTTP/1.1 and HTTP/2, synchronous and asynchronous calls, and WebSocket. This article covers synchronous use, and article 54 the asynchronous side.
The client
HttpClient client = HttpClient.newHttpClient();
gives a client with default settings. For anything else, use the builder:
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2) // the default: try HTTP/2, fall back to 1.1
.followRedirects(HttpClient.Redirect.NORMAL) // the default is NEVER
.connectTimeout(Duration.ofSeconds(5))
.cookieHandler(new CookieManager())
.proxy(ProxySelector.getDefault())
.authenticator(authenticator)
.sslContext(sslContext)
.executor(executor)
.build();
A client is immutable, thread-safe, and holds a pool of connections that it reuses. Create one per application, or per configuration, and share it. Since Java 21, HttpClient is AutoCloseable: close() waits for outstanding requests and then releases its resources. shutdown(), shutdownNow() and awaitTermination() give finer control.
Requests
Requests are immutable and built with a builder, too:
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/api/items?q=java"))
.header("Accept", "application/json")
.timeout(Duration.ofSeconds(10))
.GET() // the default
.build();
| Builder method | Purpose |
|---|---|
uri(uri) or newBuilder(uri) | the target |
GET(), POST(body), PUT(body), DELETE(), HEAD() (Java 18) | common methods |
method(name, body) | any method, such as PATCH |
header(name, value), headers(n1, v1, n2, v2, ...) | add headers |
setHeader(name, value) | replace a header |
timeout(duration) | time limit for this request's response; throws HttpTimeoutException |
version(v) | override the client's HTTP version for this request |
expectContinue(true) | ask the server before sending a large body |
Some headers, such as Host, Connection and Content-Length, are managed by the client and can't be set. HttpRequest.newBuilder(request, filter) (Java 16) copies an existing request, keeping only the headers that the BiPredicate<String, String> filter accepts. That's handy for deriving variations.
Body publishers
A request body is supplied by a BodyPublisher. The BodyPublishers class has factories for common sources:
| Publisher | Content |
|---|---|
ofString(s), ofString(s, charset) | text (UTF-8 by default) |
ofByteArray(bytes), ofByteArrays(iterable) | bytes |
ofFile(path) | a file, streamed rather than loaded |
ofInputStream(supplier) | any stream, from a supplier so the body can be resent |
noBody() | an empty body |
concat(publishers...) | several publishers in sequence (Java 16) |
ofFileChannel(channel, offset, length) | a region of a file (Java 26) |
The client doesn't know about content types. Set Content-Type yourself, and produce the format: URL-encoded forms, JSON, or multipart (article 52). Thanks to concat, a multipart upload can mix string parts with file publishers, so large files are streamed instead of read into memory, as in the demo's ofMultipart.
Responses
send takes a request and a BodyHandler that says what to do with the response body, and returns an HttpResponse<T>:
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int status = response.statusCode();
String body = response.body();
send blocks until the headers and the body (as far as the handler needs it) have arrived. It throws IOException for network failures and InterruptedException if the thread is interrupted. It does not throw for HTTP error statuses. A 404 or 500 is a normal response, so check statusCode().
Body handlers
| Handler | body() returns |
|---|---|
ofString() | the text, decoded with the charset from Content-Type (default UTF-8) |
ofByteArray() | all bytes |
ofLines() | a Stream<String> of lines, read lazily |
ofInputStream() | an InputStream to read yourself; close it when done |
ofFile(path) | the path, after saving the body there |
ofFileDownload(dir, options...) | the file in dir named by the Content-Disposition header |
discarding(), replacing(value) | nothing useful; the body is thrown away |
limiting(handler, maxBytes) | like handler, but fails if the body exceeds the limit (Java 25) |
ofPublisher(), fromSubscriber(...) | reactive-streams access |
For bodies of unknown size from servers you don't control, limiting protects your memory. Processing the content is up to you: the JDK has no JSON parser, so use a library for JSON. BodyHandlers.ofString plus a JSON library is the most common combination.
Headers and other information
response.headers() returns an HttpHeaders object. Header names are case-insensitive, and a header may have several values:
Optional<String> type = response.headers().firstValue("Content-Type");
List<String> notes = response.headers().allValues("X-Note");
OptionalLong length = response.headers().firstValueAsLong("Content-Length");
Map<String, List<String>> all = response.headers().map();
response.uri() is the final URI after redirects, and previousResponse() gives the response that led there. version() tells you whether HTTP/1.1 or HTTP/2 was used, and request() returns the request that was actually sent.
Redirects
The default policy is Redirect.NEVER, so the client returns the 3xx response as is. Redirect.NORMAL follows redirects except from https to http. Redirect.ALWAYS follows all of them. For 303 responses, and for 301/302 after a POST, the client switches to GET as browsers do.
The program
The demo talks to a local server (the JDK's HttpServer, article 55) that echoes what it receives. The client performs a GET with a custom header and inspects the response headers, then sends JSON, a form, a file with PUT, a DELETE, a PATCH and a HEAD request. It uploads a multipart body built with concat and copies a request while filtering out a header. It then tries the various body handlers, including ofFileDownload, which takes the file name from the server's Content-Disposition, and limiting. Finally, it follows a redirect, gets a 404 without an exception, and hits a request timeout.
import com.sun.net.httpserver.*;
import java.io.*;
import java.net.*;
import java.net.http.*;
import java.net.http.HttpRequest.BodyPublisher;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.Duration;
import java.util.*;
import java.util.stream.*;
public class Solution {
static HttpServer startServer() throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.createContext("/echo", ex -> {
byte[] in = ex.getRequestBody().readAllBytes();
String type = Objects.toString(ex.getRequestHeaders().getFirst("Content-Type"), "-");
String reply = ex.getRequestMethod() + " " + ex.getRequestURI() + " type=" + type
+ " length=" + in.length + (in.length > 0 && in.length < 200 ? " body=" + new String(in, StandardCharsets.UTF_8) : "")
+ " x-trace=" + ex.getRequestHeaders().getFirst("X-Trace");
byte[] out = reply.getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().set("Content-Type", "text/plain; charset=UTF-8");
ex.getResponseHeaders().add("X-Note", "first");
ex.getResponseHeaders().add("X-Note", "second");
if (ex.getRequestMethod().equals("HEAD")) ex.sendResponseHeaders(200, -1);
else { ex.sendResponseHeaders(200, out.length); ex.getResponseBody().write(out); }
ex.close();
});
server.createContext("/old", ex -> {
ex.getResponseHeaders().set("Location", "/echo?moved=yes");
ex.sendResponseHeaders(301, -1);
ex.close();
});
server.createContext("/lines", ex -> {
byte[] out = IntStream.rangeClosed(1, 5).mapToObj(i -> "line " + i).collect(Collectors.joining("\n"))
.getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().set("Content-Disposition", "attachment; filename=\"report.txt\"");
ex.sendResponseHeaders(200, out.length);
ex.getResponseBody().write(out);
ex.close();
});
server.createContext("/slow", ex -> {
try { Thread.sleep(2000); } catch (InterruptedException e) { }
ex.sendResponseHeaders(204, -1);
ex.close();
});
server.createContext("/big", ex -> {
byte[] out = "x".repeat(10_000).getBytes(StandardCharsets.UTF_8);
ex.sendResponseHeaders(200, out.length);
ex.getResponseBody().write(out);
ex.close();
});
server.start();
return server;
}
/** A form body: name=value pairs, URL-encoded. */
static BodyPublisher ofForm(Map<String, String> data) {
return BodyPublishers.ofString(data.entrySet().stream()
.map(e -> URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8) + "=" + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&")));
}
/** A multipart body that streams files instead of loading them, using concat (Java 16). */
static BodyPublisher ofMultipart(String boundary, Map<String, String> fields, Map<String, Path> files) throws FileNotFoundException {
var parts = new ArrayList<BodyPublisher>();
for (var e : fields.entrySet())
parts.add(BodyPublishers.ofString("--" + boundary + "\r\nContent-Disposition: form-data; name=\"" + e.getKey()
+ "\"\r\n\r\n" + e.getValue() + "\r\n"));
for (var e : files.entrySet()) {
parts.add(BodyPublishers.ofString("--" + boundary + "\r\nContent-Disposition: form-data; name=\"" + e.getKey()
+ "\"; filename=\"" + e.getValue().getFileName() + "\"\r\nContent-Type: application/octet-stream\r\n\r\n"));
parts.add(BodyPublishers.ofFile(e.getValue()));
parts.add(BodyPublishers.ofString("\r\n"));
}
parts.add(BodyPublishers.ofString("--" + boundary + "--\r\n"));
return BodyPublishers.concat(parts.toArray(BodyPublisher[]::new));
}
public static void main(String[] args) throws Exception {
HttpServer server = startServer();
URI base = URI.create("http://127.0.0.1:" + server.getAddress().getPort());
Path dir = Files.createTempDirectory("http");
try (HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2))
.followRedirects(HttpClient.Redirect.NORMAL)
.build()) {
System.out.println("--- GET as a String ---");
HttpRequest get = HttpRequest.newBuilder(base.resolve("/echo?q=java"))
.header("X-Trace", "abc")
.timeout(Duration.ofSeconds(5))
.build(); // GET is the default
HttpResponse<String> response = client.send(get, BodyHandlers.ofString());
System.out.println(response.statusCode() + " " + response.version() + " " + response.body());
HttpHeaders headers = response.headers();
System.out.println("content-type: " + headers.firstValue("content-type").orElse("?")
+ ", X-Note: " + headers.allValues("x-note")
+ ", length: " + headers.firstValueAsLong("Content-Length").orElse(-1));
System.out.println("--- methods and publishers ---");
Path file = dir.resolve("data.bin");
Files.write(file, new byte[1234]);
List<HttpRequest> requests = List.of(
HttpRequest.newBuilder(base.resolve("/echo")).POST(BodyPublishers.ofString("{\"a\": 1}"))
.header("Content-Type", "application/json").build(),
HttpRequest.newBuilder(base.resolve("/echo")).POST(ofForm(new TreeMap<>(Map.of("city", "San Francisco", "zip", "94105"))))
.header("Content-Type", "application/x-www-form-urlencoded").build(),
HttpRequest.newBuilder(base.resolve("/echo/item/7")).PUT(BodyPublishers.ofFile(file)).build(),
HttpRequest.newBuilder(base.resolve("/echo/item/7")).DELETE().build(),
HttpRequest.newBuilder(base.resolve("/echo")).method("PATCH", BodyPublishers.ofByteArray("op=inc".getBytes(StandardCharsets.UTF_8))).build(),
HttpRequest.newBuilder(base.resolve("/echo")).HEAD().build());
for (HttpRequest r : requests) {
HttpResponse<String> resp = client.send(r, BodyHandlers.ofString());
System.out.println(r.method() + " -> " + resp.statusCode() + " " + (resp.body().isEmpty() ? "(no body)" : resp.body()));
}
System.out.println("--- multipart upload with concat ---");
Map<String, String> fields = new TreeMap<>(Map.of("title", "Q3"));
String boundary = "boundary-" + "42";
HttpRequest upload = HttpRequest.newBuilder(base.resolve("/echo/upload"))
.header("Content-Type", "multipart/form-data; boundary=" + boundary)
.POST(ofMultipart(boundary, fields, Map.of("attachment", file))).build();
System.out.println("publisher content length: " + upload.bodyPublisher().orElseThrow().contentLength());
System.out.println(client.send(upload, BodyHandlers.ofString()).body());
System.out.println("--- copying a request with a header filter (Java 16) ---");
HttpRequest copy = HttpRequest.newBuilder(get, (name, value) -> !name.equalsIgnoreCase("X-Trace"))
.header("X-Trace", "xyz").build();
System.out.println(client.send(copy, BodyHandlers.ofString()).body());
System.out.println("--- other body handlers ---");
URI lines = base.resolve("/lines");
HttpRequest linesRequest = HttpRequest.newBuilder(lines).build();
HttpResponse<Stream<String>> streamed = client.send(linesRequest, BodyHandlers.ofLines());
try (Stream<String> s = streamed.body()) {
System.out.println("ofLines: " + s.filter(l -> !l.endsWith("3")).toList());
}
System.out.println("ofByteArray: " + client.send(linesRequest, BodyHandlers.ofByteArray()).body().length + " bytes");
try (InputStream in = client.send(linesRequest, BodyHandlers.ofInputStream()).body()) {
System.out.println("ofInputStream first line: " + new BufferedReader(new InputStreamReader(in)).readLine());
}
Path saved = client.send(linesRequest, BodyHandlers.ofFile(dir.resolve("copy.txt"))).body();
System.out.println("ofFile: " + saved.getFileName() + " has " + Files.readAllLines(saved).size() + " lines");
Path download = client.send(linesRequest, BodyHandlers.ofFileDownload(dir,
StandardOpenOption.CREATE, StandardOpenOption.WRITE)).body();
System.out.println("ofFileDownload: saved as " + download.getFileName());
System.out.println("discarding: " + client.send(linesRequest, BodyHandlers.discarding()).statusCode());
try {
client.send(HttpRequest.newBuilder(base.resolve("/big")).build(),
BodyHandlers.limiting(BodyHandlers.ofString(), 1000)); // Java 25
} catch (IOException e) {
System.out.println("limiting(…, 1000) on 10000 bytes: " + e.getClass().getSimpleName());
}
System.out.println("--- redirects, errors, timeouts ---");
HttpResponse<String> moved = client.send(HttpRequest.newBuilder(base.resolve("/old")).build(), BodyHandlers.ofString());
System.out.println("followed to " + moved.uri().getPath() + "?" + moved.uri().getQuery()
+ ", previous status " + moved.previousResponse().map(HttpResponse::statusCode).orElse(0));
System.out.println("missing page: status " + client.send(
HttpRequest.newBuilder(base.resolve("/nope")).build(), BodyHandlers.discarding()).statusCode() + ", no exception");
try {
client.send(HttpRequest.newBuilder(base.resolve("/slow")).timeout(Duration.ofMillis(300)).build(),
BodyHandlers.discarding());
} catch (HttpTimeoutException e) {
System.out.println("HttpTimeoutException: " + e.getMessage());
}
} finally {
server.stop(0);
try (var files = Files.list(dir)) {
for (Path p : files.toList()) Files.delete(p);
}
Files.delete(dir);
}
}
}
--- GET as a String ---
200 HTTP_1_1 GET /echo?q=java type=- length=0 x-trace=abc
content-type: text/plain; charset=UTF-8, X-Note: [first, second], length: 44
--- methods and publishers ---
POST -> 200 POST /echo type=application/json length=8 body={"a": 1} x-trace=null
POST -> 200 POST /echo type=application/x-www-form-urlencoded length=28 body=city=San+Francisco&zip=94105 x-trace=null
PUT -> 200 PUT /echo/item/7 type=- length=1234 x-trace=null
DELETE -> 200 DELETE /echo/item/7 type=- length=0 x-trace=null
PATCH -> 200 PATCH /echo type=- length=6 body=op=inc x-trace=null
HEAD -> 200 (no body)
--- multipart upload with concat ---
publisher content length: 1449
POST /echo/upload type=multipart/form-data; boundary=boundary-42 length=1449 x-trace=null
--- copying a request with a header filter (Java 16) ---
GET /echo?q=java type=- length=0 x-trace=xyz
--- other body handlers ---
ofLines: [line 1, line 2, line 4, line 5]
ofByteArray: 34 bytes
ofInputStream first line: line 1
ofFile: copy.txt has 5 lines
ofFileDownload: saved as report.txt
discarding: 200
limiting(…, 1000) on 10000 bytes: IOException
--- redirects, errors, timeouts ---
followed to /echo?moved=yes, previous status 301
missing page: status 404, no exception
HttpTimeoutException: request timed out
Common questions
Why does my GET not follow redirects?
The default redirect policy is NEVER. Build the client with .followRedirects(HttpClient.Redirect.NORMAL).
How do I set a timeout for the whole request?
HttpRequest.Builder.timeout(Duration) limits the time until the response headers arrive (an HttpTimeoutException otherwise). HttpClient.Builder.connectTimeout limits connection setup. On JDK 25, neither limits reading a slow body (a body that trickles in after the headers is still delivered after the timeout); for that, read the body with a streaming handler and enforce your own deadline, or use sendAsync with orTimeout.
Why do I get "restricted header name: Host"?
The client manages Host, Connection, Content-Length, Expect and Upgrade itself and rejects attempts to set them with IllegalArgumentException. jdk.httpclient.allowRestrictedHeaders (a system property listing names) relaxes this, but rarely is it needed.
How do I add the same header, such as an authorization token, to every request?
Write a small helper that creates a builder with the common headers, or copy a template request with HttpRequest.newBuilder(template, (n, v) -> true). For Basic or proxy authentication that responds to a 401, set an Authenticator on the client.
Can I use HttpClient with HTTP/3?
Since JDK 26 (JEP 517), yes: HttpClient.Version.HTTP_3 can be requested on the client or the request. It's opt-in; the default preference stays HTTP/2 with fallback to HTTP/1.1. On JDK 25, the versions are HTTP/1.1 and HTTP/2. Article 54 covers HTTP/3 discovery.
What is the default User-Agent?
Java-http-client/ followed by the JDK version, for example Java-http-client/25.0.5. Set your own with .header("User-Agent", ...), which the client allows.
API reference
| API | Purpose |
|---|---|
HttpClient.newHttpClient(), HttpClient.newBuilder()...build() | create a client |
Builder.version, followRedirects, connectTimeout, cookieHandler, authenticator, proxy, sslContext, executor | client settings |
HttpClient.send(request, handler) | synchronous request |
HttpClient.close(), shutdown(), awaitTermination(d) | release the client (Java 21) |
HttpRequest.newBuilder(uri), GET, POST, PUT, DELETE, HEAD, method | build requests |
header, setHeader, timeout, expectContinue | request options |
HttpRequest.newBuilder(request, filter) | copy a request with filtered headers (Java 16) |
BodyPublishers.ofString, ofByteArray, ofFile, ofInputStream, noBody, concat | request bodies |
BodyHandlers.ofString, ofByteArray, ofLines, ofInputStream, ofFile, ofFileDownload, discarding, limiting | response bodies |
HttpResponse.statusCode(), body(), headers(), uri(), version(), previousResponse() | response information |
HttpHeaders.firstValue, allValues, firstValueAsLong, map | headers |
HttpTimeoutException, HttpConnectTimeoutException | timeouts |
Summary
- Build one
HttpClientwith the settings you need, share it, and close it when you're done. - Build immutable
HttpRequests with a URI, method, headers, timeout and a body publisher. - Body publishers send strings, bytes, files or streams.
concatcomposes multipart bodies. SetContent-Typeyourself. sendreturns anHttpResponse<T>whose body type is chosen by the body handler: string, bytes, lines, stream, file or download.- HTTP errors are ordinary responses, so check
statusCode(). Redirects are followed only if the client is configured for it.
Practice Questions
Why should an application reuse one HttpClient instead of creating one per request?
A client keeps a pool of open connections, HTTP/2 sessions and TLS sessions that later requests can reuse, which saves round trips and handshakes. It's also thread-safe. Creating one per request throws all of that away and wastes resources until each client is closed or garbage collected.
client.send(request, BodyHandlers.ofString()) returns normally, but the page wasn't found. How do you detect that?
send only throws for transport problems. An HTTP 404 is a successful exchange from the client's point of view. Check response.statusCode(), for example if (response.statusCode() >= 400) ....
How would you send a PATCH request with a JSON body?
HttpRequest.newBuilder(uri).header("Content-Type", "application/json").method("PATCH", BodyPublishers.ofString(json)).build(). The builder has dedicated methods only for GET, POST, PUT, DELETE and HEAD, and method covers the others.
You download files of unknown size from user-supplied URLs. Which body handler choices protect your program?
Stream the body to disk with ofFile or ofFileDownload, or process it incrementally with ofInputStream or ofLines instead of ofString or ofByteArray. To cap the size, wrap the handler with BodyHandlers.limiting(handler, maxBytes) (Java 25), which fails once the body exceeds the limit.
A client built with HttpClient.newHttpClient() gets a 302 response instead of the page. Why?
The default redirect policy is Redirect.NEVER. Build the client with .followRedirects(HttpClient.Redirect.NORMAL) to follow redirects (except from HTTPS to HTTP), or handle the Location header yourself.
Previous: Posting Form Data in Java: GET and POST, URL Encoding and Multipart
Next: Asynchronous HTTP and WebSocket in Java: sendAsync, HTTP/2 and WebSocket
Related reading
- Posting Form Data in Java: GET and POST, URL Encoding and Multipart
- URIs, URLs and URLConnection in Java: Retrieving Web Data and Headers
- Interruptible Sockets and TLS in Java: SocketChannel, Virtual Threads and SSLSocket
- Java Server Sockets: Serving Multiple Clients with Threads and Virtual Threads
- Java Sockets: Connecting to a Server, Timeouts and InetAddress

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.