Asynchronous HTTP and WebSocket in Java: sendAsync, HTTP/2 and WebSocket
Use HttpClient asynchronously: sendAsync and CompletableFuture pipelines, running many requests in parallel, combining and timing out futures, executors, HTTP/2 and HTTP/3 (Java 26) version negotiation, and the WebSocket API with listeners, fragments, pings and closing.
kvi5hnuCode Sprout team member11 min readOn this page
Article 53 used HttpClient.send, which blocks the calling thread until the response arrives. That is fine on a virtual thread, but sometimes you want to start a request, do something else, and react to the response later. You may also want to fire off dozens of requests at once and gather the results. sendAsync gives you that. The same client also opens WebSocket connections, which are long-lived two-way channels between a client and a server. This article covers both.
sendAsync and CompletableFuture
sendAsync(request, handler) takes the same arguments as send but returns at once with a CompletableFuture<HttpResponse<T>>. The future completes when the response headers and body have arrived (or exceptionally when the exchange fails). You then chain steps onto it:
CompletableFuture<String> price = client
.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenApply(body -> "tea costs " + body);
Nothing in this chain blocks. Each thenApply runs when the previous stage completes. At the end, you can block with get or join, or keep composing.
These are the CompletableFuture methods you will use most (the concurrency part of the course covers them in depth):
| Method | Effect |
|---|---|
thenApply(f) | transform the result |
thenAccept(c) | consume the result |
thenCompose(f) | chain another asynchronous step, such as a second request that depends on the first |
thenCombine(other, f) | combine two independent results |
exceptionally(f), handle(f) | recover from failures |
orTimeout(t, unit), completeOnTimeout(v, t, unit) | fail, or use a default, if the result is late |
CompletableFuture.allOf(...), anyOf(...) | wait for all, or for the first |
A failed exchange completes the future exceptionally. join then throws a CompletionException and get throws an ExecutionException, and each wraps the real cause, for example an HttpConnectTimeoutException or ConnectException. As with send, an HTTP error status like 404 is an ordinary response, not an exception.
Many requests in parallel
The main use of sendAsync is fan-out: start every request, then wait for them all.
List<CompletableFuture<String>> futures = items.stream()
.map(item -> client.sendAsync(requestFor(item), BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.exceptionally(ex -> "failed: " + ex))
.toList();
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join();
List<String> results = futures.stream().map(CompletableFuture::join).toList();
The total time is roughly that of the slowest request instead of the sum of all of them. Put exceptionally on each future so one failure doesn't spoil the whole batch.
Executors and cancellation
The client runs its internal work and your dependent stages on an executor. By default it creates its own thread pool. You can supply your own with HttpClient.newBuilder().executor(...), for example Executors.newVirtualThreadPerTaskExecutor(). If you need stages to run on a particular executor, use the ...Async(f, executor) variants of the chaining methods.
Calling cancel(true) on the future returned by sendAsync attempts to abort the exchange (supported since Java 16). Closing the client with close() or shutdownNow() (Java 21) also stops outstanding requests.
Push promises
HTTP/2 servers can push resources the client hasn't asked for yet. The overload sendAsync(request, handler, pushPromiseHandler) lets you accept or reject each push. PushPromiseHandler.of(...) collects accepted pushes into a map of futures. Server push is rarely used and the major browsers have dropped it, so you are unlikely to need this.
HTTP versions
HttpClient prefers HTTP/2 by default. You can force a version with Builder.version(...) on the client or on an individual request.
- Over
https, the client offers HTTP/2 during the TLS handshake (ALPN). If the server doesn't accept it, the connection falls back to HTTP/1.1. - Over plain
http, the client sends an HTTP/1.1 request with anUpgrade: h2cheader. Servers that don't support upgrading simply answer in HTTP/1.1.
response.version() tells you which version was actually used. With HTTP/2, many requests to the same server share one connection, so firing many async requests at one host costs only one TCP and TLS setup.
WebSocket
HTTP is request and response: the client asks, the server answers. WebSocket (RFC 6455) starts as an HTTP request with an Upgrade: websocket header. If the server agrees (status 101), the TCP connection then carries messages in both directions until one side closes it. That suits chat, live dashboards, games and notifications.
Opening a connection
WebSocket ws = client.newWebSocketBuilder()
.connectTimeout(Duration.ofSeconds(5))
.header("Authorization", "Bearer " + token)
.subprotocols("chat.v1")
.buildAsync(URI.create("wss://example.com/chat"), listener)
.join();
The URI scheme is ws or wss (WebSocket over TLS). buildAsync completes with a WebSocket once the handshake succeeds. If the server refuses, it fails with a WebSocketHandshakeException, whose getResponse() shows the HTTP response.
Receiving: the listener
Incoming events go to a WebSocket.Listener. Every method has a default implementation, so you override only what you need:
| Method | Called when |
|---|---|
onOpen(ws) | the connection is ready |
onText(ws, data, last) | text arrives. last is false while more parts of the same message follow |
onBinary(ws, data, last) | binary data arrives, as a ByteBuffer |
onPing(ws, msg), onPong(ws, msg) | control messages arrive. The implementation answers every ping with a pong by itself, even if you override onPing |
onClose(ws, code, reason) | the server sent a close message |
onError(ws, error) | the connection failed. No further events follow |
Two rules are easy to get wrong:
- Flow control. The listener gets nothing until you request it.
ws.request(n)allowsnmore events. The defaultonOpencallsrequest(1), and the default receive methods request one more after each event. If you override them, callrequest(1)yourself or the stream stalls. - Partial messages. A large message may arrive in several pieces. Collect them until
lastis true. TheCharSequenceorByteBufferpassed to you is only valid until the returnedCompletionStagecompletes (or right away if you returnnull), so copy the data out.
Sending
sendText(data, last), sendBinary(buffer, last), sendPing, sendPong and sendClose(code, reason) each return a CompletableFuture<WebSocket>. Only one send may be outstanding at a time. Wait for the previous one, or chain sends with thenCompose, or you get an IllegalStateException. To send a message in pieces, pass last = false for all but the final part.
sendClose(WebSocket.NORMAL_CLOSURE, "bye") (code 1000) starts an orderly shutdown. The output side closes at once, and the server answers with its own close message, which arrives in onClose. abort() drops the connection without the closing exchange. isOutputClosed() and isInputClosed() report the state.
The program
The demo starts a local HttpServer whose /price handler waits 200 ms before answering, like a slow back end. One sendAsync call shows that the future isn't done when the call returns. Eight requests then run in parallel, including one that yields a 404, and they finish in about the time of one. Two futures are combined, and a too-slow request trips orTimeout. A request for HTTP/2 over plain HTTP falls back to HTTP/1.1, because the JDK's simple server doesn't upgrade. Finally, a WebSocket session sends a text message, a message in two fragments, binary data and a ping, and then closes the connection.
import com.sun.net.httpserver.*;
import java.io.*;
import java.net.*;
import java.net.http.*;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
public class Solution {
// ---------------- an HTTP server for the async part ----------------
static HttpServer startHttpServer() throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
server.createContext("/price", ex -> {
String item = ex.getRequestURI().getQuery().substring("item=".length());
try { Thread.sleep(200); } catch (InterruptedException e) { } // a slow back end
byte[] out = String.valueOf(item.length() * 10 + 5).getBytes(StandardCharsets.UTF_8);
int status = item.equals("unknown") ? 404 : 200;
ex.sendResponseHeaders(status, out.length);
ex.getResponseBody().write(out);
ex.close();
});
server.start();
return server;
}
// ---------------- a minimal WebSocket echo server (RFC 6455) ----------------
static ServerSocket startWebSocketServer() throws IOException {
var server = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
Thread.ofVirtual().start(() -> {
try (server; Socket s = server.accept()) {
var in = new DataInputStream(new BufferedInputStream(s.getInputStream()));
OutputStream out = s.getOutputStream();
String key = null;
for (String line = readLine(in); !line.isEmpty(); line = readLine(in))
if (line.toLowerCase(Locale.ROOT).startsWith("sec-websocket-key:")) key = line.substring(18).strip();
String accept = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1").digest(
(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes(StandardCharsets.US_ASCII)));
out.write(("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
+ "Sec-WebSocket-Accept: " + accept + "\r\n\r\n").getBytes(StandardCharsets.US_ASCII));
out.flush();
var message = new ByteArrayOutputStream(); // collects fragments
int messageOpcode = 0;
while (true) {
int b0 = in.readUnsignedByte(), b1 = in.readUnsignedByte();
boolean fin = (b0 & 0x80) != 0;
int opcode = b0 & 0x0F;
long len = b1 & 0x7F;
if (len == 126) len = in.readUnsignedShort();
else if (len == 127) len = in.readLong();
byte[] mask = new byte[4];
in.readFully(mask); // client frames are always masked
byte[] payload = new byte[(int) len];
in.readFully(payload);
for (int i = 0; i < payload.length; i++) payload[i] ^= mask[i % 4];
if (opcode == 0x1 || opcode == 0x2 || opcode == 0x0) { // data frame or continuation
if (opcode != 0x0) messageOpcode = opcode;
message.write(payload);
if (!fin) continue; // wait for the final fragment
payload = message.toByteArray();
message.reset();
opcode = messageOpcode;
}
if (opcode == 0x8) { // close: echo it and stop
writeFrame(out, 0x8, payload);
break;
} else if (opcode == 0x9) { // ping -> pong
writeFrame(out, 0xA, payload);
} else if (opcode == 0x1) { // text: answer in upper case
String text = new String(payload, StandardCharsets.UTF_8);
writeFrame(out, 0x1, ("ECHO " + text.toUpperCase(Locale.ROOT)).getBytes(StandardCharsets.UTF_8));
} else if (opcode == 0x2) { // binary: report the size
writeFrame(out, 0x1, ("got " + payload.length + " bytes").getBytes(StandardCharsets.UTF_8));
}
}
} catch (Exception e) {
System.out.println("ws server: " + e);
}
});
return server;
}
static String readLine(DataInputStream in) throws IOException {
var sb = new StringBuilder();
for (int c = in.read(); c != '\n'; c = in.read()) if (c != '\r') sb.append((char) c);
return sb.toString();
}
static void writeFrame(OutputStream out, int opcode, byte[] payload) throws IOException {
out.write(0x80 | opcode); // FIN + opcode, unmasked
out.write(payload.length); // short frames only
out.write(payload);
out.flush();
}
public static void main(String[] args) throws Exception {
HttpServer http = startHttpServer();
URI base = URI.create("http://127.0.0.1:" + http.getAddress().getPort());
try (HttpClient client = HttpClient.newBuilder()
.executor(Executors.newVirtualThreadPerTaskExecutor())
.connectTimeout(Duration.ofSeconds(2)).build()) {
System.out.println("--- one asynchronous request ---");
CompletableFuture<String> future = client
.sendAsync(HttpRequest.newBuilder(base.resolve("/price?item=tea")).build(), BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenApply(body -> "tea costs " + body);
System.out.println("returned at once, done: " + future.isDone());
System.out.println(future.get(5, TimeUnit.SECONDS));
System.out.println("--- many requests in parallel ---");
List<String> items = List.of("tea", "coffee", "biscuits", "cake", "jam", "unknown", "bread", "milk");
long start = System.nanoTime();
List<CompletableFuture<String>> futures = items.stream()
.map(item -> client.sendAsync(HttpRequest.newBuilder(base.resolve("/price?item=" + item)).build(), BodyHandlers.ofString())
.thenApply(r -> r.statusCode() == 200 ? item + "=" + r.body() : item + ": HTTP " + r.statusCode())
.exceptionally(ex -> item + ": failed " + ex))
.toList();
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join();
long millis = Duration.ofNanos(System.nanoTime() - start).toMillis();
System.out.println(futures.stream().map(CompletableFuture::join).toList());
System.out.println("8 requests of 200 ms each finished in well under 1600 ms: " + (millis < 1200));
System.out.println("--- combining and racing ---");
CompletableFuture<Integer> tea = client.sendAsync(HttpRequest.newBuilder(base.resolve("/price?item=tea")).build(),
BodyHandlers.ofString()).thenApply(r -> Integer.parseInt(r.body()));
CompletableFuture<Integer> cake = client.sendAsync(HttpRequest.newBuilder(base.resolve("/price?item=cake")).build(),
BodyHandlers.ofString()).thenApply(r -> Integer.parseInt(r.body()));
System.out.println("tea + cake = " + tea.thenCombine(cake, Integer::sum).get(5, TimeUnit.SECONDS));
CompletableFuture<String> slow = client.sendAsync(HttpRequest.newBuilder(base.resolve("/price?item=jam")).build(),
BodyHandlers.ofString()).thenApply(HttpResponse::body).orTimeout(50, TimeUnit.MILLISECONDS);
try {
slow.join();
} catch (CompletionException e) {
System.out.println("orTimeout(50 ms): " + e.getCause().getClass().getSimpleName());
}
System.out.println("--- HTTP version negotiation ---");
HttpResponse<Void> r = client.send(HttpRequest.newBuilder(base.resolve("/price?item=x"))
.version(HttpClient.Version.HTTP_2).build(), BodyHandlers.discarding());
System.out.println("asked for HTTP/2 over plain http, server speaks " + r.version());
System.out.println("--- WebSocket ---");
ServerSocket wsServer = startWebSocketServer();
var received = new LinkedBlockingQueue<String>();
WebSocket.Listener listener = new WebSocket.Listener() {
private final StringBuilder partial = new StringBuilder();
@Override public void onOpen(WebSocket ws) {
received.add("open");
ws.request(1);
}
@Override public CompletionStage<?> onText(WebSocket ws, CharSequence data, boolean last) {
partial.append(data);
if (last) { received.add("text: " + partial); partial.setLength(0); }
ws.request(1); // ask for the next message
return null;
}
@Override public CompletionStage<?> onPong(WebSocket ws, java.nio.ByteBuffer message) {
received.add("pong: " + StandardCharsets.UTF_8.decode(message));
ws.request(1);
return null;
}
@Override public CompletionStage<?> onClose(WebSocket ws, int statusCode, String reason) {
received.add("closed " + statusCode + " " + reason);
return null;
}
@Override public void onError(WebSocket ws, Throwable error) {
received.add("error " + error);
}
};
WebSocket ws = client.newWebSocketBuilder()
.connectTimeout(Duration.ofSeconds(2))
.buildAsync(URI.create("ws://127.0.0.1:" + wsServer.getLocalPort() + "/chat"), listener)
.get(5, TimeUnit.SECONDS);
ws.sendText("hello", true).join();
System.out.println(received.poll(5, TimeUnit.SECONDS));
System.out.println(received.poll(5, TimeUnit.SECONDS));
ws.sendText("split ", false).thenCompose(w -> w.sendText("message", true)).join();
System.out.println(received.poll(5, TimeUnit.SECONDS));
ws.sendBinary(java.nio.ByteBuffer.wrap(new byte[42]), true).join();
System.out.println(received.poll(5, TimeUnit.SECONDS));
ws.sendPing(java.nio.ByteBuffer.wrap("are you there?".getBytes(StandardCharsets.UTF_8))).join();
System.out.println(received.poll(5, TimeUnit.SECONDS));
ws.sendClose(WebSocket.NORMAL_CLOSURE, "bye").join();
System.out.println(received.poll(5, TimeUnit.SECONDS));
System.out.println("output closed: " + ws.isOutputClosed());
} finally {
http.stop(0);
}
}
}
--- one asynchronous request ---
returned at once, done: false
tea costs 35
--- many requests in parallel ---
[tea=35, coffee=65, biscuits=85, cake=45, jam=35, unknown: HTTP 404, bread=55, milk=45]
8 requests of 200 ms each finished in well under 1600 ms: true
--- combining and racing ---
tea + cake = 80
orTimeout(50 ms): TimeoutException
--- HTTP version negotiation ---
asked for HTTP/2 over plain http, server speaks HTTP_1_1
--- WebSocket ---
open
text: ECHO HELLO
text: ECHO SPLIT MESSAGE
text: got 42 bytes
pong: are you there?
closed 1000 bye
output closed: true
Common questions
How do I limit how many requests run at once?
sendAsync doesn't limit anything; a thousand calls start a thousand exchanges. Guard them with a Semaphore (acquire before sendAsync, release in whenComplete), or use virtual threads with a semaphore around send. Servers often rate-limit, so also be ready for status 429 with a Retry-After header.
How do I retry a failed request?
Wrap the call in a method that, on exceptionallyCompose (Java 12), schedules another attempt with a delay, for example using CompletableFuture.delayedExecutor, up to a maximum count. Only retry idempotent requests (GET, PUT, DELETE) automatically, and use exponential backoff. With virtual threads, an ordinary loop with Thread.sleep is simpler.
Why does my WebSocket listener stop receiving messages?
Usually because request(n) isn't called again. The default onOpen requests one message, and each default onText/onBinary requests one more. If you override them, call webSocket.request(1) yourself after each message.
Does HttpClient reconnect a WebSocket automatically?
No. When onClose or onError runs, the connection is gone. Reconnect from there with buildAsync, with a delay, and resubscribe whatever the application protocol requires.
Can the JDK act as a WebSocket server? Not out of the box. Use Jakarta WebSocket (in Tomcat, Jetty and others), Spring, Netty, or Undertow. The demo's mini server is for illustration only.
Does join() on many futures block one thread per future?
No. CompletableFuture.allOf(...).join() blocks only the calling thread until all are complete. The exchanges themselves run on the client's executor and selector thread.
API reference
| API | Purpose |
|---|---|
HttpClient.sendAsync(request, handler) | start a request, returns CompletableFuture<HttpResponse<T>> |
sendAsync(request, handler, pushPromiseHandler) | also handle HTTP/2 server pushes |
CompletableFuture.thenApply, thenCompose, thenCombine, exceptionally, orTimeout, allOf, join | compose and wait for results |
HttpClient.Builder.executor(executor) | the executor for the client's work |
HttpClient.Version.HTTP_1_1, HTTP_2, HTTP_3 (Java 26) | preferred protocol version |
HttpOption.H3_DISCOVERY, Http3DiscoveryMode (Java 26) | how HTTP/3 support is discovered |
HttpResponse.version() | the version actually used |
HttpClient.newWebSocketBuilder(), WebSocket.Builder.header, subprotocols, connectTimeout, buildAsync(uri, listener) | open a WebSocket |
WebSocket.Listener.onOpen, onText, onBinary, onPing, onPong, onClose, onError | receive events |
WebSocket.request(n) | allow n more incoming events |
WebSocket.sendText, sendBinary, sendPing, sendPong, sendClose, abort | send messages, close |
WebSocket.isOutputClosed(), isInputClosed(), getSubprotocol() | connection state |
WebSocketHandshakeException.getResponse() | the server's response to a refused handshake |
Summary
sendAsyncreturns aCompletableFutureat once. ChainthenApply,thenComposeandthenCombineto process results without blocking.- For fan-out, start all requests, add
exceptionallyto each, thenallOf(...).join(). The total time is close to the slowest request. - Failures complete the future exceptionally and are wrapped in
CompletionExceptionorExecutionException. HTTP error statuses are normal responses. - The client prefers HTTP/2 and falls back to HTTP/1.1. Java 26 adds opt-in HTTP/3 with a choice of discovery modes.
- WebSocket: open with
newWebSocketBuilder().buildAsync, receive through aListener(callrequest(1)and assemble partial messages), send one message at a time, and finish withsendClose.
Practice Questions
You need prices from 50 URLs. How do you fetch them with sendAsync so one bad URL doesn't make you lose the others?
Map each URL to client.sendAsync(...).thenApply(HttpResponse::body).exceptionally(ex -> fallback), collect the futures into a list, call CompletableFuture.allOf(array).join(), then join() each future. Because each future recovers on its own, allOf never fails, and you get a result or fallback for every URL. Without exceptionally, allOf completes exceptionally if any request fails.
What is the difference between thenApply and thenCompose when chaining requests?
thenApply applies an ordinary function to the result. If that function itself calls sendAsync, you end up with a CompletableFuture<CompletableFuture<...>>. thenCompose takes a function that returns a future and flattens it, so use it when the second request depends on the first one's response.
Your WebSocket listener overrides onOpen and onText. It receives the first message and then nothing more. Why?
Incoming messages are flow-controlled. Each request(n) call allows n more events, and overriding the default methods removes their automatic request(1). Call ws.request(1) in onOpen and at the end of each onText (and the other receive methods).
Why might ws.sendText("a", true); ws.sendText("b", true); throw an IllegalStateException?
Only one send may be in progress at a time. The second call starts before the first send's future has completed. Wait for it with join(), or chain the sends: ws.sendText("a", true).thenCompose(w -> w.sendText("b", true)).
You set .version(HttpClient.Version.HTTP_2) but response.version() says HTTP_1_1. Is something broken?
Not necessarily. The version setting is a preference. Over https the server must agree via ALPN, and over plain http the server must support the h2c upgrade. If it doesn't, the client falls back to HTTP/1.1. That is what happens with the JDK's built-in HttpServer, which speaks only HTTP/1.1.
Previous: The Java HttpClient: Requests, Responses, Body Publishers and Handlers
Next: A Simple HTTP Server in Java: jwebserver, HttpServer, Handlers and Filters
Related reading
- The Java HttpClient: Requests, Responses, Body Publishers and Handlers
- 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

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.