00:00

HTTP Client API in Java 11

Last updated: · Standard (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

TypeRoleCreated with
HttpClientsends requests; holds settings such as timeouts, redirects and HTTP versionHttpClient.newHttpClient() or newBuilder()
HttpRequestan immutable request: URI, method, headers, bodyHttpRequest.newBuilder(uri)
HttpResponse<T>status, headers and a body converted by a BodyHandlerreturned by send / sendAsync
Syntax.java
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

HttpClientBasics.java
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);
    }
}
Output
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.

AsyncAndPost.java
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);
    }
}
Output
Request sent, doing other work...
Response: 201 created ORDER-42

4. How a Request Flows

Request and response flow of the Java 11 HTTP Client An HttpRequest is built, the shared HttpClient sends it, the server answers, and a BodyHandler converts the body into the type of HttpResponse. HttpRequest URI, method, headers HttpClient send / sendAsync Server returns status + body HttpResponse<T> body via BodyHandler
Figure 1: The request is immutable, the client is reusable, and the BodyHandler decides the Java type of the body.

5. Before and After Java 11

AspectHttpURLConnectionJava 11 HttpClient
API stylemutable, stream-basedfluent builders, immutable requests
HTTP/2not supportedsupported, negotiated automatically
Async callsnonesendAsync with CompletableFuture
Body conversionmanual stream readingBodyHandlers.ofString(), ofFile(), ...

6. Important Points and Best Practices

  • Create one HttpClient and reuse it; it manages a connection pool and is thread-safe.
  • Set a connectTimeout on the client and a timeout on 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, HttpClient implements AutoCloseable, 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 reusable HttpClient, read an HttpResponse.
  • Use send for blocking calls and sendAsync for non-blocking ones.
  • Configure timeouts and redirects explicitly.

Related Tutorials

8. References