HTTP Client API in Java 11
The HTTP Client API in the java.net.http module is the modern, built-in way to call web services from Java. It was incubated in Java 9 and 10 and became a standard API in Java 11 (JEP 321), supporting HTTP/1.1, HTTP/2, synchronous and asynchronous requests.
This tutorial covers the three main types, a blocking GET, an asynchronous POST, and the settings you should know for production code. The examples start a small local server, so they run without internet access.
1. Why Was a New HTTP Client Needed?
The old HttpURLConnection dates from Java 1.1. It is hard to use, supports only HTTP/1.1, works only in blocking mode, and needs a lot of code for simple tasks. Most teams added Apache HttpClient or OkHttp instead. The new client offers a fluent, immutable API, HTTP/2, and non-blocking calls based on CompletableFuture, with no extra dependency.
2. The Three Main Types
| Type | Role | Created with |
|---|---|---|
HttpClient | sends requests; holds settings such as timeouts, redirects and HTTP version | HttpClient.newHttpClient() or newBuilder() |
HttpRequest | an immutable request: URI, method, headers, body | HttpRequest.newBuilder(uri) |
HttpResponse<T> | status, headers and a body converted by a BodyHandler | returned by send / sendAsync |
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/api"))
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
3. Practical Examples
Example 1: A synchronous GET request
import com.sun.net.httpserver.HttpServer;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
public class HttpClientBasics {
public static void main(String[] args) throws Exception {
// A tiny local server so the example runs without internet access
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/greeting", exchange -> {
byte[] body = "{\"message\":\"Hello from the server\"}".getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(200, body.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(body);
}
});
server.start();
String base = "http://127.0.0.1:" + server.getAddress().getPort();
// One client can be reused for many requests
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
HttpRequest request = HttpRequest.newBuilder(URI.create(base + "/greeting"))
.header("Accept", "application/json")
.GET()
.build();
// Synchronous call: blocks until the response arrives
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status : " + response.statusCode());
System.out.println("Content-Type : " + response.headers().firstValue("Content-Type").orElse("?"));
System.out.println("Body : " + response.body());
server.stop(0);
}
}
Status : 200
Content-Type : application/json
Body : {"message":"Hello from the server"}
BodyHandlers.ofString() turns the response body into a String. Other handlers write to a file (ofFile) or give you a stream (ofInputStream).
Example 2: An asynchronous POST request
sendAsync returns immediately with a CompletableFuture, so the calling thread can do other work while the request is in flight.
import com.sun.net.httpserver.HttpServer;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
public class AsyncAndPost {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
// Echo the request body back in upper case
server.createContext("/orders", exchange -> {
String received = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
byte[] reply = ("created " + received.toUpperCase()).getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(201, reply.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(reply);
}
});
server.start();
URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/orders");
HttpClient client = HttpClient.newHttpClient();
// POST with a String body
HttpRequest post = HttpRequest.newBuilder(uri)
.header("Content-Type", "text/plain")
.POST(HttpRequest.BodyPublishers.ofString("order-42"))
.build();
// sendAsync returns a CompletableFuture instead of blocking
CompletableFuture<String> result = client.sendAsync(post, HttpResponse.BodyHandlers.ofString())
.thenApply(r -> r.statusCode() + " " + r.body());
System.out.println("Request sent, doing other work...");
System.out.println("Response: " + result.join());
server.stop(0);
}
}
Request sent, doing other work... Response: 201 created ORDER-42
4. How a Request Flows
5. Before and After Java 11
| Aspect | HttpURLConnection | Java 11 HttpClient |
|---|---|---|
| API style | mutable, stream-based | fluent builders, immutable requests |
| HTTP/2 | not supported | supported, negotiated automatically |
| Async calls | none | sendAsync with CompletableFuture |
| Body conversion | manual stream reading | BodyHandlers.ofString(), ofFile(), ... |
6. Important Points and Best Practices
- Create one
HttpClientand reuse it; it manages a connection pool and is thread-safe. - Set a
connectTimeouton the client and atimeouton each request; there is no timeout by default. - Redirects are not followed unless you set
followRedirects(Redirect.NORMAL). - A non-2xx status is not an exception; always check
statusCode(). - Since Java 21,
HttpClientimplementsAutoCloseable, so it can be used in try-with-resources.
7. Summary
- The HTTP Client became a standard API in Java 11 (JEP 321), in module
java.net.http. - Build an
HttpRequest, send it with a reusableHttpClient, read anHttpResponse. - Use
sendfor blocking calls andsendAsyncfor non-blocking ones. - Configure timeouts and redirects explicitly.
Related Tutorials
8. References
Frequently Asked Questions (FAQ)
Q1. Which Java version added the standard HTTP Client?
Java 11, through JEP 321. It was an incubator module in Java 9 and 10 under a different package name.
Q2. What is the difference between send and sendAsync?
send blocks until the response is available. sendAsync returns a CompletableFuture<HttpResponse> immediately and completes it later.
Q3. Does the Java 11 HttpClient support HTTP/2?
Yes. It prefers HTTP/2 when the server supports it and falls back to HTTP/1.1 otherwise. You can force a version with version(HttpClient.Version.HTTP_1_1).
Q4. Does HttpClient throw an exception for a 404 response?
No. Any HTTP response, including 4xx and 5xx, is returned normally. Exceptions are thrown only for problems such as connection failures or timeouts.