Java HttpClient
The Java HttpClient (java.net.http.HttpClient) is the built-in way to send HTTP requests and receive responses in Java. It became a standard part of the JDK in Java 11 and replaces the old HttpURLConnection with a clean builder API, HTTP/2 support and asynchronous requests.
You use HttpClient whenever a Java program talks to a web server: calling a REST API, downloading a file or checking whether a website is up. This lesson covers creating and configuring a client, sending synchronous and asynchronous requests, reading responses, handling redirects and timeouts, and closing the client.
The Three Main Types of the HttpClient API
The API lives in the java.net.http package and is built around three types.
| Type | Role | Created with |
|---|---|---|
HttpClient | Sends requests; holds settings and reusable connections | HttpClient.newHttpClient() or HttpClient.newBuilder() |
HttpRequest | Describes one request: URI, method, headers, body | HttpRequest.newBuilder(uri) |
HttpResponse<T> | The result: status code, headers and a body of type T | Returned by send() or sendAsync() |
A body handler (HttpResponse.BodyHandlers) tells the client how to turn the response body into a Java object, for example a String or a file.
A Local Test Server for the Examples
Every example in this lesson talks to a small server running on your own computer, so the code works without internet access and the output is always the same. Save this class as DemoServer.java next to each example.
// FILE: DemoServer.java
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.Executors;
// A tiny HTTP server on http://localhost:8090 used by the examples
public class DemoServer {
static final Map<String, String> ORDERS = Map.of(
"1001", "1001,SHIPPED,2499.00",
"1002", "1002,PACKED,899.50",
"1003", "1003,DELIVERED,15999.00");
public static HttpServer start() throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 8090), 0);
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor()); // handle requests in parallel
server.createContext("/hello", ex -> send(ex, 200, "text/plain", "Hello from DemoServer"));
server.createContext("/products", ex -> send(ex, 200, "application/json",
"[{\"id\":1,\"name\":\"Keyboard\",\"price\":1200},{\"id\":2,\"name\":\"Mouse\",\"price\":450}]"));
server.createContext("/old-page", ex -> {
ex.getResponseHeaders().add("Location", "/hello");
send(ex, 301, "text/plain", "Moved");
});
server.createContext("/slow", ex -> {
sleep(2000); // a slow endpoint
send(ex, 200, "text/plain", "Finally done");
});
server.createContext("/orders/", ex -> {
String id = ex.getRequestURI().getPath().substring("/orders/".length());
sleep(300);
String order = ORDERS.get(id);
if (order == null) send(ex, 404, "text/plain", "Order " + id + " not found");
else send(ex, 200, "text/csv", order);
});
server.createContext("/", ex -> send(ex, 404, "text/plain", "Not found"));
server.start();
return server;
}
static void send(HttpExchange exchange, int status, String contentType, String text) throws IOException {
byte[] body = text.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", contentType);
exchange.sendResponseHeaders(status, body.length);
exchange.getResponseBody().write(body);
exchange.close();
}
static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
The server has five endpoints: /hello (plain text), /products (JSON), /old-page (a redirect to /hello), /slow (answers after 2 seconds) and /orders/{id} (an order in CSV form, or 404). For a real API, just replace http://localhost:8090 with its address.
Your First GET Request with Java HttpClient
Sending a request takes four steps: create a client, build a request, call send() with a body handler, and read the response.
Syntax:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com")).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class FirstRequest {
public static void main(String[] args) throws Exception {
HttpServer server = DemoServer.start();
try (HttpClient client = HttpClient.newHttpClient()) {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8090/hello"))
.GET() // GET is the default, so this line is optional
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode());
System.out.println("Body : " + response.body());
} finally {
server.stop(0);
}
}
}
Output:
Status: 200
Body : Hello from DemoServer
How it works:
HttpClient.newHttpClient()creates a client with default settings.HttpRequest.newBuilder(uri)starts a request;build()makes it immutable, so it can be sent many times.client.send(...)is synchronous: it blocks until the whole response has arrived.BodyHandlers.ofString()turns the body into aString.- Since Java 21,
HttpClientimplementsAutoCloseable, so try-with-resources shuts it down and frees its threads and connections.
Note:
send()declaresIOException(network problems) andInterruptedException(the waiting thread was interrupted). An error status such as404or500does not throw; you must checkstatusCode()yourself.
Configuring the HttpClient with newBuilder()
HttpClient.newBuilder() lets you change the client's settings. Create one client with the settings you need and reuse it for every request; it keeps connections open and shares them.
| Builder method | Default | Purpose |
|---|---|---|
version(HttpClient.Version) | HTTP_2 | Preferred HTTP version; falls back to HTTP/1.1 if the server cannot do HTTP/2 |
connectTimeout(Duration) | No timeout | Maximum time to open a connection |
followRedirects(HttpClient.Redirect) | NEVER | NEVER, NORMAL (not from HTTPS to HTTP) or ALWAYS |
executor(Executor) | Built-in pool | Threads used for asynchronous work |
proxy(ProxySelector) | System default | Send requests through a proxy |
authenticator(Authenticator) | None | Supply user name and password when a server asks |
cookieHandler(CookieHandler) | None | Store and send cookies, e.g. new CookieManager() |
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class ConfiguredClient {
public static void main(String[] args) throws Exception {
HttpServer server = DemoServer.start();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8090/old-page")).build();
// Default client: redirects are NOT followed
try (HttpClient plain = HttpClient.newHttpClient()) {
HttpResponse<String> response = plain.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Default : " + response.statusCode() + ", Location = "
+ response.headers().firstValue("Location").orElse("-"));
}
// Configured client: follows redirects and has a connect timeout
try (HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL)
.build()) {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Followed: " + response.statusCode() + " from " + response.uri());
System.out.println("Body : " + response.body());
response.previousResponse().ifPresent(previous ->
System.out.println("Redirected from " + previous.uri() + " (" + previous.statusCode() + ")"));
System.out.println("Settings: " + client.version() + ", connect timeout "
+ client.connectTimeout().orElseThrow().toSeconds() + " s");
} finally {
server.stop(0);
}
}
}
Output:
Default : 301, Location = /hello
Followed: 200 from http://localhost:8090/hello
Body : Hello from DemoServer
Redirected from http://localhost:8090/old-page (301)
Settings: HTTP_1_1, connect timeout 5 s
How it works:
- The default client returns the
301response itself, and you can read the new address from theLocationheader. - With
Redirect.NORMAL, the client follows the redirect automatically.response.uri()shows the final address, andpreviousResponse()gives the redirect response that led there. - The client's settings can be read back with getters such as
version()andconnectTimeout().
Reading the HttpResponse
An HttpResponse gives you everything the server sent back.
| Method | Returns |
|---|---|
statusCode() | The status code, e.g. 200, 404 |
body() | The body, converted by the body handler |
headers() | All response headers as an HttpHeaders object |
uri() | The URI of the response (after redirects) |
version() | The HTTP version actually used |
request() | The request that produced this response |
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ReadResponse {
public static void main(String[] args) throws Exception {
HttpServer server = DemoServer.start();
try (HttpClient client = HttpClient.newHttpClient()) {
for (String path : new String[]{"/products", "/missing-page"}) {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8090" + path)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.request().method() + " " + response.uri());
System.out.println(" version : " + response.version());
System.out.println(" status : " + response.statusCode()
+ (response.statusCode() == 200 ? " (success)" : " (error)"));
System.out.println(" content-type : " + response.headers().firstValue("content-type").orElse("none"));
System.out.println(" length : " + response.headers().firstValueAsLong("Content-Length").orElse(-1));
System.out.println(" body : " + response.body());
}
} finally {
server.stop(0);
}
}
}
Output:
GET http://localhost:8090/products
version : HTTP_1_1
status : 200 (success)
content-type : application/json
length : 77
body : [{"id":1,"name":"Keyboard","price":1200},{"id":2,"name":"Mouse","price":450}]
GET http://localhost:8090/missing-page
version : HTTP_1_1
status : 404 (error)
content-type : text/plain
length : 9
body : Not found
How it works:
- The client asked for HTTP/2, but the test server only speaks HTTP/1.1, so
version()shows the version that was really used. - Header names are case-insensitive:
firstValue("content-type")findsContent-Type.firstValueAsLong()parses a number header. - The
404response is returned normally, with its own body, so your code decides what an error means.
Choosing a Body Handler
The body handler decides what type body() returns. Pick the one that fits the data.
| Body handler | body() type | Use it for |
|---|---|---|
BodyHandlers.ofString() | String | Text, JSON, HTML |
BodyHandlers.ofByteArray() | byte[] | Small binary files such as images |
BodyHandlers.ofFile(Path) | Path | Downloading straight to disk |
BodyHandlers.ofLines() | Stream<String> | Large text, processed line by line |
BodyHandlers.ofInputStream() | InputStream | Reading the body yourself as it arrives |
BodyHandlers.discarding() | Void | When you only need the status and headers |
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
public class BodyHandlerDemo {
public static void main(String[] args) throws Exception {
HttpServer server = DemoServer.start();
HttpRequest productsRequest = HttpRequest.newBuilder(URI.create("http://localhost:8090/products")).build();
try (HttpClient client = HttpClient.newHttpClient()) {
// 1. Raw bytes
HttpResponse<byte[]> bytes = client.send(productsRequest, HttpResponse.BodyHandlers.ofByteArray());
System.out.println("ofByteArray : " + bytes.body().length + " bytes");
// 2. Save to a file
Path target = Files.createTempFile("products", ".json");
HttpResponse<Path> saved = client.send(productsRequest, HttpResponse.BodyHandlers.ofFile(target));
System.out.println("ofFile : saved " + Files.size(saved.body()) + " bytes to a .json file");
Files.delete(target);
// 3. Ignore the body, keep only the status
HttpRequest helloRequest = HttpRequest.newBuilder(URI.create("http://localhost:8090/hello")).build();
HttpResponse<Void> statusOnly = client.send(helloRequest, HttpResponse.BodyHandlers.discarding());
System.out.println("discarding : status " + statusOnly.statusCode() + ", body " + statusOnly.body());
// 4. Stream of lines
HttpResponse<java.util.stream.Stream<String>> lines =
client.send(helloRequest, HttpResponse.BodyHandlers.ofLines());
System.out.println("ofLines : " + lines.body().map(String::toUpperCase).toList());
} finally {
server.stop(0);
}
}
}
Output:
ofByteArray : 77 bytes
ofFile : saved 77 bytes to a .json file
discarding : status 200, body null
ofLines : [HELLO FROM DEMOSERVER]
How it works:
- The same
HttpRequestis sent several times with different handlers; requests are immutable and reusable. ofFile(target)writes the body to disk while it downloads and returns thePath, which keeps large downloads out of memory.discarding()reads and throws away the body, sobody()isnull.ofLines()returns aStream<String>, so you can process a large text response line by line with the Stream API.
Asynchronous Requests with sendAsync()
sendAsync() sends a request without blocking. It immediately returns a CompletableFuture<HttpResponse<T>> that completes when the response arrives. This lets one thread fire many requests at once.
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class AsyncRequests {
public static void main(String[] args) throws Exception {
HttpServer server = DemoServer.start();
try (HttpClient client = HttpClient.newHttpClient()) {
HttpRequest slowRequest = HttpRequest.newBuilder(URI.create("http://localhost:8090/slow")).build();
long start = System.nanoTime();
// Fire three slow requests at once; each takes about 2 seconds on the server
List<CompletableFuture<String>> futures = List.of(1, 2, 3).stream()
.map(number -> client.sendAsync(slowRequest, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> "request " + number + ": " + response.body()))
.toList();
System.out.println("All 3 requests sent, main thread is free");
// Wait for all of them, then print the results in order
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
futures.forEach(future -> System.out.println(future.join()));
long seconds = (System.nanoTime() - start) / 1_000_000_000;
System.out.println("Total time about " + seconds + " seconds, not 6");
} finally {
server.stop(0);
}
}
}
Output:
All 3 requests sent, main thread is free
request 1: Finally done
request 2: Finally done
request 3: Finally done
Total time about 2 seconds, not 6
How it works:
sendAsync()returns at once, so the message "All 3 requests sent" appears before any response.thenApply()transforms each response into aStringwhen it arrives, without blocking.CompletableFuture.allOf(...).join()waits until every request has finished. The three requests overlapped, so the total time is about 2 seconds instead of 6.- The Java CompletableFuture lesson explains
thenApply,allOfand error handling withexceptionallyin detail.
Handling Timeouts and Network Errors
A request timeout set with HttpRequest.Builder.timeout() limits how long the client waits for the response. When it expires, send() throws HttpTimeoutException. Connection problems throw other IOException subclasses.
| Exception | Cause |
|---|---|
HttpTimeoutException | The response did not arrive within the request timeout |
HttpConnectTimeoutException | The connection could not be opened within the client's connect timeout |
ConnectException | Nothing is listening at that host and port |
IOException | Other network errors |
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.time.Duration;
public class TimeoutsAndErrors {
static void fetch(HttpClient client, String url, Duration timeout) throws InterruptedException {
HttpRequest request = HttpRequest.newBuilder(URI.create(url)).timeout(timeout).build();
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(url + " -> " + response.statusCode() + " " + response.body());
} catch (HttpTimeoutException e) {
System.out.println(url + " -> timed out after " + timeout.toMillis() + " ms");
} catch (IOException e) {
System.out.println(url + " -> failed: " + e.getClass().getSimpleName());
}
}
public static void main(String[] args) throws Exception {
HttpServer server = DemoServer.start();
try (HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build()) {
fetch(client, "http://localhost:8090/hello", Duration.ofSeconds(1));
fetch(client, "http://localhost:8090/slow", Duration.ofMillis(500));
fetch(client, "http://localhost:8090/slow", Duration.ofSeconds(5));
fetch(client, "http://localhost:8099/hello", Duration.ofSeconds(1)); // no server here
} finally {
server.stop(0);
}
}
}
Output:
http://localhost:8090/hello -> 200 Hello from DemoServer
http://localhost:8090/slow -> timed out after 500 ms
http://localhost:8090/slow -> 200 Finally done
http://localhost:8099/hello -> failed: ConnectException
How it works:
/slowneeds 2 seconds. With a 500 ms timeout the client gives up and throwsHttpTimeoutException; with 5 seconds it succeeds.- Port 8099 has no server, so the connection is refused with
ConnectException. HttpTimeoutExceptionis a subclass ofIOException, so itscatchblock must come first.
Note: Set both a connect timeout on the client and a request timeout on each request. Without them, a server that never answers can block your thread for a very long time.
Real-World Example: An Order Status Dashboard
A support dashboard must show the status of several orders at once. Each order is a separate API call that takes about 300 ms, so calling them one by one is slow. This program sends all calls asynchronously with one shared client, handles missing orders and errors per order, and prints a summary.
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class OrderDashboard {
record OrderStatus(String id, String status, double amount, String error) {
boolean found() { return error == null; }
}
static final String API = "http://localhost:8090/orders/";
static CompletableFuture<OrderStatus> fetchOrder(HttpClient client, String orderId) {
HttpRequest request = HttpRequest.newBuilder(URI.create(API + orderId))
.timeout(Duration.ofSeconds(3))
.header("Accept", "text/csv")
.build();
return client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> {
if (response.statusCode() != 200) {
return new OrderStatus(orderId, "-", 0, "HTTP " + response.statusCode());
}
String[] fields = response.body().split(","); // id,status,amount
return new OrderStatus(fields[0], fields[1], Double.parseDouble(fields[2]), null);
})
.exceptionally(error -> new OrderStatus(orderId, "-", 0, error.getClass().getSimpleName()));
}
public static void main(String[] args) throws Exception {
HttpServer server = DemoServer.start();
List<String> orderIds = List.of("1001", "1002", "1003", "1004", "1005");
try (HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2))
.build()) {
long start = System.nanoTime();
List<CompletableFuture<OrderStatus>> futures = orderIds.stream()
.map(id -> fetchOrder(client, id))
.toList();
List<OrderStatus> orders = futures.stream().map(CompletableFuture::join).toList();
long millis = (System.nanoTime() - start) / 1_000_000;
System.out.println("ORDER STATUS AMOUNT (Rs)");
double total = 0;
for (OrderStatus order : orders) {
if (order.found()) {
System.out.printf("%-6s %-10s %12.2f%n", order.id(), order.status(), order.amount());
total += order.amount();
} else {
System.out.printf("%-6s %-10s %12s%n", order.id(), "ERROR", order.error());
}
}
long foundCount = orders.stream().filter(OrderStatus::found).count();
System.out.printf("Found %d of %d orders, total Rs %.2f%n", foundCount, orders.size(), total);
System.out.println("Fetched in parallel: " + (millis < 1000));
} finally {
server.stop(0);
}
}
}
Output:
ORDER STATUS AMOUNT (Rs)
1001 SHIPPED 2499.00
1002 PACKED 899.50
1003 DELIVERED 15999.00
1004 ERROR HTTP 404
1005 ERROR HTTP 404
Found 3 of 5 orders, total Rs 19397.50
Fetched in parallel: true
How it works:
- One shared client. A single
HttpClientsends every request and reuses connections. Creating a new client per request would waste time and resources. - One future per order.
fetchOrder()builds a request with a timeout and anAcceptheader, then callssendAsync(). All five requests are in flight at the same time. - Turning responses into records.
thenApply()converts a200response from CSV into anOrderStatus, and turns any other status into an error entry, so a missing order never stops the dashboard. - Catching failures.
exceptionally()handles network errors and timeouts the same way, by returning anOrderStatusthat describes the error. - Collecting in order.
join()on each future waits for its result. The five calls of about 300 ms each run at the same time, so the whole dashboard loads in well under a second.
The next lesson, Java HTTP requests, shows how to send POST, PUT and DELETE requests with headers and JSON bodies. For the URI handling used here, see the Java URI class.