Skip to content
Tutorials Center
My learning

Topics

Lesson 143 of 201 ยท Networking

The Java HTTP Client

Learn the java.net.http HttpClient - GET and POST requests, headers, status codes, body handlers, async calls, timeouts and redirects, tested against a local HttpServer.

Most programs that talk to other programs today speak HTTP: REST APIs, payment providers, weather services, webhooks, cloud storage. Since Java 11, the standard library includes a modern HTTP client in the java.net.http module. It builds immutable requests with a fluent builder, supports HTTP/1.1 and HTTP/2, can run calls synchronously or asynchronously with CompletableFuture, and handles redirects, timeouts and body conversion for you. You no longer need a third-party library for everyday HTTP calls.

Our sandbox has no internet, so every example here does what professional tests do too: it starts a small HTTP server inside the same program, using the JDK's built-in com.sun.net.httpserver.HttpServer, on 127.0.0.1 and a free port. The client code is exactly what you'd write against a real API; only the URL would change. This lesson builds on TCP Sockets, because HTTP is a text protocol that runs over a TCP connection.

The three main types

The API revolves around three classes, all in java.net.http:

  • HttpClient holds settings shared by many requests (timeouts, redirect policy, HTTP version, proxy, executor) and a pool of connections. Create one and reuse it: creating a client per request throws away its connection pool.
  • HttpRequest describes one request: URI, method, headers, body and timeout. It's immutable and built with HttpRequest.newBuilder().
  • HttpResponse<T> is the result: status code, headers, HTTP version and a body of type T, which a BodyHandler produces (a String, a byte[], a file, a stream of lines, ...).
Java
HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.example.com/items/7"))
        .header("Accept", "application/json")
        .GET()                                  // the default method
        .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode() + " " + response.body());

send blocks until the full response has arrived and throws IOException for network failures and InterruptedException if the thread is interrupted. Since Java 21, HttpClient also implements AutoCloseable, so short programs can close it with try-with-resources.

Your first GET request

The example below starts a server with two endpoints, /hello and /time-zone, and calls them with the client. The server part is plain JDK code: createContext maps a path to a handler, and the handler writes a status line, headers and a body through the HttpExchange.

Java GET requests against a local server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The response reports HTTP_1_1. The client prefers HTTP/2 by default, but over plain http:// the server must agree to upgrade, and the JDK's simple server doesn't, so the two sides settle on HTTP/1.1 automatically. With https:// and a server that supports it, the same code uses HTTP/2 with no changes. Headers are case-insensitive, so firstValue("content-type") would find the same header.

com.sun.net.httpserver is a supported, documented JDK module (jdk.httpserver), despite the com.sun name. It's ideal for tests, tools and demos. For production web services you'd use a framework such as Spring Boot, covered in the Advanced Java track.

POST requests, headers and status codes

To send data, pick a method on the builder and give it a BodyPublisher: BodyPublishers.ofString(text), ofByteArray(bytes), ofFile(path) or noBody(). Set the Content-Type header yourself; the client doesn't guess it.

One important behavior surprises many developers: HTTP error statuses don't throw exceptions. A 404 or 500 is still a successful HTTP exchange, so send returns normally and you must check statusCode() yourself. Exceptions are reserved for failures to communicate at all (refused connection, timeout, broken stream).

Java POST with a JSON body and checking status codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

PUT, DELETE and GET have their own builder methods; any other verb (for example PATCH) uses .method("PATCH", publisher). The 404 for /nothing-here comes from the JDK server itself, because no context matches that path.

Building URLs and form data safely

Never glue untrusted text into a URL or form body: a space, & or # in a value changes the meaning of the whole request. Encode each value with URLEncoder.encode(value, StandardCharsets.UTF_8):

Java
String query = "city=" + URLEncoder.encode("Sรฃo Paulo & more", StandardCharsets.UTF_8);
URI uri = URI.create("https://api.example.com/weather?" + query);
// https://api.example.com/weather?city=S%C3%A3o+Paulo+%26+more

HttpRequest form = HttpRequest.newBuilder(URI.create("https://example.com/login"))
        .header("Content-Type", "application/x-www-form-urlencoded")
        .POST(HttpRequest.BodyPublishers.ofString("user=" + URLEncoder.encode(user, StandardCharsets.UTF_8)))
        .build();

For JSON bodies in real projects, build and parse the text with a library such as Jackson instead of string concatenation; the Advanced Java track shows how.

Body handlers: choosing the response type

The BodyHandler you pass to send decides what response.body() returns:

Handler Body type Use it for
BodyHandlers.ofString() String Text and JSON (uses the charset from Content-Type, else UTF-8)
BodyHandlers.ofByteArray() byte[] Images, binary formats
BodyHandlers.ofFile(path) Path Downloads straight to disk, without holding them in memory
BodyHandlers.ofLines() Stream<String> Large line-based responses, processed as they arrive
BodyHandlers.ofInputStream() InputStream Custom streaming parsers
BodyHandlers.discarding() Void When only the status and headers matter

ofString and ofByteArray load the entire body into memory, which is fine for API responses but not for a 4 GB download. Use ofFile or a streaming handler for large content.

Asynchronous requests

sendAsync returns a CompletableFuture<HttpResponse<T>> immediately and completes it when the response arrives. That lets you fire several requests at once and combine the results, without managing threads yourself. In the next example each server endpoint takes 300 ms to answer. Called one after another they'd take about 900 ms; sent asynchronously they overlap and finish in roughly 300 ms.

Java Three requests in parallel with sendAsync

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The server needs an executor here; by default HttpServer handles one exchange at a time, which would serialize the three requests and hide the benefit. Async calls are great for fan-out (calling several services and combining their answers). With virtual threads, plain blocking send calls on separate threads are an equally good, often simpler alternative.

Timeouts, redirects and errors

A client that talks to real servers must not wait forever. There are two separate timeouts:

  • HttpClient.newBuilder().connectTimeout(Duration) limits how long opening a TCP connection may take.
  • HttpRequest.newBuilder().timeout(Duration) limits how long the whole request may take until the response headers arrive; when it expires, send throws HttpTimeoutException (a subclass of IOException).

Redirects are not followed by default (Redirect.NEVER): you get the 301/302 response and its Location header. followRedirects(HttpClient.Redirect.NORMAL) follows them, except from https to http, which would downgrade security.

Java Request timeouts and following redirects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

r2.uri() is the URI of the final response, after redirects, which is handy for logging. In production code, wrap calls in a small helper that sets a timeout on every request, checks the status code and retries only safe, idempotent requests (such as GET) after timeouts or 5xx errors, with a growing delay between attempts.

Configuring the client

HttpClient.newBuilder() gathers the settings that apply to every request:

Java
HttpClient client = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_2)            // default; falls back to 1.1
        .connectTimeout(Duration.ofSeconds(5))
        .followRedirects(HttpClient.Redirect.NORMAL)
        .proxy(ProxySelector.of(new InetSocketAddress("proxy.internal", 3128)))
        .authenticator(myAuthenticator)                // for Basic auth challenges
        .cookieHandler(new CookieManager())            // keep cookies between requests
        .executor(Executors.newVirtualThreadPerTaskExecutor())
        .build();

Two practical rules: make one client per application (or per remote service with special settings) and share it, and set default headers, such as an API key or User-Agent, in a helper that creates request builders, because HttpClient has no "default headers" option.

The legacy HttpURLConnection

Before Java 11, the only built-in option was java.net.HttpURLConnection. You'll still see it in older code and libraries:

Java
URL url = URI.create("https://api.example.com/items").toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5_000);
connection.setReadTimeout(5_000);
int status = connection.getResponseCode();
try (InputStream in = status < 400 ? connection.getInputStream() : connection.getErrorStream()) {
    String body = new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
connection.disconnect();

It works, but it's mutable, has no async support or HTTP/2, uses awkward stream rules (error bodies come from a different method, getInputStream throws for status 400 and above) and has easy-to-forget defaults such as infinite timeouts. Prefer HttpClient in all new code. For HTTP itself (methods, status codes, caching, authentication) and advanced client topics such as streaming uploads, WebSockets and testing, continue with HTTP Basics and The HTTP Client in Depth.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A request to an API returns status 404. What does client.send(request, BodyHandlers.ofString()) do?

    HTTP error statuses are valid responses, so send returns normally. Exceptions are only for communication failures such as refused connections or timeouts.
  2. 2. Why should an application reuse a single HttpClient instead of creating one per request?

    An HttpClient is immutable, thread-safe and holds pooled connections. Sharing it lets requests reuse open connections, which is much faster.
  3. 3. A server answers /old with status 302 and a Location header. What does a client from HttpClient.newHttpClient() return?

    The default redirect policy is NEVER. Use followRedirects(HttpClient.Redirect.NORMAL) on the builder to follow redirects automatically.
  4. 4. Which body handler is the best choice for downloading a 3 GB file?

    ofFile streams the body to disk as it arrives. ofString and ofByteArray keep the whole body in memory, and discarding throws it away.
  5. 5. What does HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(2)) limit?

    The request timeout covers waiting for the response. The connection-opening phase has its own setting, connectTimeout on the HttpClient builder.

Summary

  • java.net.http has three core types: a reusable HttpClient, immutable HttpRequests built with a builder, and HttpResponse<T> with a body produced by a BodyHandler.
  • send blocks; sendAsync returns a CompletableFuture, which makes parallel calls easy. HttpClient is AutoCloseable since Java 21.
  • Send data with POST/PUT/method(...) and a BodyPublisher, set Content-Type yourself, and URL-encode query and form values.
  • Status codes like 404 and 500 don't throw: always check statusCode(). Network failures throw IOException, and timeouts throw HttpTimeoutException.
  • Redirects are off by default (Redirect.NORMAL turns them on); set a connect timeout on the client and a request timeout on each request.
  • com.sun.net.httpserver.HttpServer is a handy built-in server for tests and demos; prefer HttpClient over the legacy HttpURLConnection.

Next: Java GUI Overview: AWT, Swing and JavaFX, where you'll meet Java's desktop toolkits and see how they differ.