Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท I/O and Files

The HttpClient class

Reference for java.net.http.HttpClient: build requests, send them synchronously or asynchronously, read responses with body handlers, set timeouts and headers.

java.net.http.HttpClient (standard since Java 11) is the built-in HTTP client. It supports HTTP/1.1 and HTTP/2, synchronous and asynchronous calls, redirects, timeouts, cookies, proxies and WebSocket. You build one immutable client, reuse it for many requests, and describe each call with an HttpRequest.

The sandbox on this page has no internet access, so remote calls are shown as read-only snippets. The runnable examples talk to a tiny server on 127.0.0.1 that the program starts itself (see com.sun.net.httpserver).

Java
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/")).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

Try it

Read-only: typical calls against a real server. Run these on your own machine.

Java
HttpClient client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(5))
        .followRedirects(HttpClient.Redirect.NORMAL)
        .build();

// GET
HttpRequest get = HttpRequest.newBuilder(URI.create("https://api.example.com/users/1"))
        .header("Accept", "application/json")
        .timeout(Duration.ofSeconds(10))
        .GET()
        .build();
HttpResponse<String> res = client.send(get, HttpResponse.BodyHandlers.ofString());
System.out.println(res.statusCode() + " " + res.body());

// POST with a JSON body
HttpRequest post = HttpRequest.newBuilder(URI.create("https://api.example.com/users"))
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString("{\"name\":\"Ann\"}"))
        .build();
Java GET and POST against a loopback 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.

Java Asynchronous requests 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.

Syntax

Java
public abstract class HttpClient
static HttpClient newHttpClient()
static HttpClient.Builder newBuilder()
<T> HttpResponse<T> send(HttpRequest request, HttpResponse.BodyHandler<T> handler)
        throws IOException, InterruptedException
<T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest request, HttpResponse.BodyHandler<T> handler)
Builder / class Description
HttpClient.Builder.connectTimeout(Duration) Maximum time to establish a connection.
.followRedirects(HttpClient.Redirect) NEVER (default), NORMAL (not HTTPS to HTTP), ALWAYS.
.version(HttpClient.Version) HTTP_2 (default, falls back) or HTTP_1_1.
.executor(Executor), .proxy(...), .authenticator(...), .cookieHandler(...) Threads for async work, proxy, credentials, cookies.
HttpRequest.newBuilder(URI) Starts a request; .GET(), .POST(publisher), .PUT(...), .DELETE(), .method(name, publisher).
HttpRequest.Builder.header(name, value), .timeout(Duration) Headers and the per-request response timeout.
BodyPublishers.ofString/ofByteArray/ofFile/noBody Request bodies.
BodyHandlers.ofString/ofByteArray/ofFile/ofLines/ofInputStream/discarding How the response body is consumed.

Throws: IOException (connection problems, HttpTimeoutException, ConnectException), InterruptedException from send, IllegalArgumentException for a bad request (for example a URI without a scheme).

Usage notes

  • Reuse the client. It owns a connection pool and selector thread. Create it once, not per request.
  • Status codes are not exceptions. A 404 or 500 returns normally; check statusCode().
  • Two different timeouts. connectTimeout is on the client, timeout is on each request and covers waiting for the response headers.
  • Redirects are off by default. Add followRedirects(NORMAL) or you will receive the 301/302 itself.
  • Body handlers choose memory use. ofString loads everything; ofFile, ofInputStream and ofLines stream large bodies.
  • Immutable and thread safe. Both HttpClient and HttpRequest can be shared between threads.
  • sendAsync returns a CompletableFuture; compose it with thenApply. It uses the client's executor or a default pool of daemon threads.
  • Daemon threads. A program with only async requests can exit before they finish, because the default threads are daemons.
  • Closing. HttpClient implements AutoCloseable only from Java 21 (close() waits for requests to finish); older versions have no close method.
  • Restricted headers such as Host and Content-Length cannot be set by hand; the client manages them.