HttpClient, HttpRequest and HttpResponse
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A ShopLite program needs product data that lives in another program, the ShopLite API. Before Java 11 one call took pages of stream code; now the JDK sends it in a few lines.
java.net.http: three types that work together
java.net.http is the JDK package (Java 11 and later) for sending HTTP requests from Java code. Its three main types are HttpClient (the sender), HttpRequest (one call) and HttpResponse<T> (the answer: status, headers and body).
Your program often needs data from another program, such as the product list from the ShopLite API. Build a client once, build a request, call client.send, then read the response.
Example 1 · Your first GET from Java
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;import java.io.IOException;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;
/** A tiny stand-in for the ShopLite API, so the example runs without internet. */class FakeShopApi { static HttpServer start() throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/products/1", exchange -> reply(exchange, 200, "{\"id\":1,\"sku\":\"MOB-RN13\",\"name\":\"Redmi Note 13 5G\",\"price\":17999.00,\"stock\":40}")); server.start(); return server; }
static void reply(HttpExchange exchange, int status, String json) throws IOException { byte[] body = json.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "application/json"); exchange.sendResponseHeaders(status, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }}
public class FirstGetDemo { public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = FakeShopApi.start(); String baseUrl = "http://127.0.0.1:" + server.getAddress().getPort(); // http://localhost:8080 in real life try { HttpClient client = HttpClient.newHttpClient(); // 1. the sender
HttpRequest request = HttpRequest.newBuilder() // 2. what to send .uri(URI.create(baseUrl + "/api/v1/products/1")) .GET() .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); } }}Status: 200
Body: {"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","price":17999.00,"stock":40}What this code does
- The three types appear in order:
HttpClient(the sender),HttpRequest(GET/api/v1/products/1) andHttpResponse<String>(the answer). BodyHandlers.ofString()turns the body into aString, soresponse.body()is the JSON text exactly as the server sent it. Turning that text into a Java object comes in the Jackson lesson of this module.server.stop(0)infinallystops the test server even if a call fails, so the program always ends.
HttpClient holds settings and keeps network connections open. HttpRequest holds the method, the URL, the headers and an optional body. HttpResponse<T> holds the status code, the headers and a body of type T. The body handler you pass to send tells Java what to turn the body into, for example a String.
Before Java 11 the only built-in option was HttpURLConnection, which needs many lines of stream code for one GET; HttpClient does the same in about five.
FakeShopApi), so it runs on any computer without internet. Its port is chosen by the system, so it never clashes with other programs. In a real app the URL is something like http://localhost:8080. The Tiny HTTP server module explains how such a server works; here, read only main.Building one reusable HttpClient
HttpClient is the object that sends HTTP requests. It is immutable (its settings never change after it is built) and thread-safe (many threads can use it at the same time), and it keeps a pool of open connections for reuse.
HttpClient.newHttpClient() creates a client with default settings; newBuilder()...build() sets options such as timeouts. Build it once and reuse it for every call.
Example 2 · One shared client reuses its connection
import com.sun.net.httpserver.HttpServer;import java.io.IOException;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.HashSet;import java.util.Set;
/** A stand-in API that remembers which connection each request arrived on. */class CountingApi { final Set<Integer> connections = new HashSet<>(); // one client port = one TCP connection HttpServer server;
void start() throws IOException { server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/products", exchange -> { connections.add(exchange.getRemoteAddress().getPort()); byte[] body = "{\"ok\":true}".getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "application/json"); exchange.sendResponseHeaders(200, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }); server.start(); }
String baseUrl() { return "http://127.0.0.1:" + server.getAddress().getPort(); }}
public class SharedClientDemo { private static final HttpClient CLIENT = HttpClient.newHttpClient(); // built once, used everywhere
static int fetch(HttpClient client, String url) throws IOException, InterruptedException { HttpRequest request = HttpRequest.newBuilder(URI.create(url)).build(); return client.send(request, HttpResponse.BodyHandlers.ofString()).statusCode(); }
public static void main(String[] args) throws IOException, InterruptedException { CountingApi api = new CountingApi(); api.start(); try { for (int id = 1; id <= 3; id++) { fetch(CLIENT, api.baseUrl() + "/api/v1/products/" + id); } System.out.println("Shared client: 3 requests, " + api.connections.size() + " connection(s)");
api.connections.clear(); for (int id = 1; id <= 3; id++) { HttpClient fresh = HttpClient.newHttpClient(); fetch(fresh, api.baseUrl() + "/api/v1/products/" + id); } System.out.println("New client per call: 3 requests, " + api.connections.size() + " connection(s)"); } finally { api.server.stop(0); } }}Shared client: 3 requests, 1 connection(s) New client per call: 3 requests, 3 connection(s)
What this code does
- The test server records the client-side port of each request. One port means one TCP connection.
- The shared
CLIENTsends three requests over 1 connection. A newHttpClientper call opens 3 connections for the same work, and each of those clients starts its own background thread. - With HTTPS, every extra connection also pays for a TLS handshake, so reuse matters even more against a real API.
Reuse matters because opening a TCP connection takes time, and an HTTPS connection also needs a TLS handshake. A shared client reuses an open connection for the next request to the same server. A new client per call opens a new connection every time, and each client also starts its own background thread.
Keep one client for the whole app:
- Create it once, at startup. Never inside a loop or inside a method that runs per request.
- Use a
private static finalfield in a small program, or pass it to your classes through their constructors in a bigger one. - On Java 21 and later,
HttpClientalso hasclose(). On Java 17 there is noclose(); an unused client is cleaned up by the garbage collector.
A GET request with HttpRequest.newBuilder and send
HttpRequest is one immutable HTTP request: the method, the address (a java.net.URI), the headers and an optional body. You make it with HttpRequest.newBuilder() and finish with build().
Chain .uri(...), .header(...) and .GET() on HttpRequest.newBuilder(), finish with .build(), then pass the request to client.send(...).
Example 3 · Building and inspecting a request
import com.sun.net.httpserver.HttpServer;import java.io.IOException;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;
/** A stand-in API that prints what each request asked for. */class EchoApi { static HttpServer start() throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/categories", exchange -> { System.out.println(" server got: " + exchange.getRequestMethod() + " " + exchange.getRequestURI() + ", Accept = " + exchange.getRequestHeaders().getFirst("Accept")); byte[] body = "[{\"id\":2,\"name\":\"Mobiles\"},{\"id\":3,\"name\":\"Laptops\"}]".getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "application/json"); exchange.sendResponseHeaders(200, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }); server.start(); return server; }}
public class RequestBuilderDemo { private static final HttpClient CLIENT = HttpClient.newHttpClient();
public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = EchoApi.start(); String baseUrl = "http://127.0.0.1:" + server.getAddress().getPort(); try { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(baseUrl + "/api/v1/categories?parent=1")) .header("Accept", "application/json") .GET() .build();
System.out.println("Method: " + request.method()); System.out.println("Path: " + request.uri().getPath() + "?" + request.uri().getQuery()); System.out.println("Accept: " + request.headers().firstValue("Accept").orElse("(none)"));
System.out.println("Sending twice:"); for (int i = 1; i <= 2; i++) { HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(" try " + i + ": status " + response.statusCode() + ", body " + response.body()); } } finally { server.stop(0); } }}Method: GET
Path: /api/v1/categories?parent=1
Accept: application/json
Sending twice:
server got: GET /api/v1/categories?parent=1, Accept = application/json
try 1: status 200, body [{"id":2,"name":"Mobiles"},{"id":3,"name":"Laptops"}]
server got: GET /api/v1/categories?parent=1, Accept = application/json
try 2: status 200, body [{"id":2,"name":"Mobiles"},{"id":3,"name":"Laptops"}]What this code does
newBuilder()chains the URI, anAcceptheader and the method, thenbuild()returns an immutableHttpRequest. Its parts can be read back withmethod(),uri()andheaders().- The same request object is sent twice and works both times. Build a request once if you call the same URL again and again.
- The "server got" lines are printed by the test server while
sendwaits, which shows thatsendblocks until the answer arrives.
Example 4 · Mistake: send without handling its checked exceptions
import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;
public class NoThrowsDemo { public static void main(String[] args) { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8080/api/v1/products/1")).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode()); }}NoThrowsDemo.java:11: error: unreported exception IOException; must be caught or declared to be thrown
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
^
1 errorWhat this code does
senddeclaresthrows IOException, InterruptedException, and both are checked exceptions, sojavacrefuses the call until you handle them.- The quick fix is
public static void main(String[] args) throws IOException, InterruptedException, as in the other examples. In real classes, the Handling network failures lesson shows how to catch them properly.
GET is the default, so .GET() is optional, but writing it makes the code easier to read. A built request is immutable, so you can send the same request again. client.send(request, handler) blocks: the current thread waits until the whole response has arrived. It throws two checked exceptions, IOException (the network failed) and InterruptedException (another thread asked this one to stop while it waited), so your method must catch them or declare them with throws.
Common errors here are small but real: a URL with a space or without http:// throws IllegalArgumentException at URI.create or build(), and setting a header that Java controls itself, such as Host, throws IllegalArgumentException: restricted header name: "Host".
Order of execution
Order a GET call
Put the steps of one GET call in the order your code runs them.
Reading status, headers and body
A body handler is the object you pass to send that tells Java how to turn the response body into a Java value, such as BodyHandlers.ofString() for a String.
BodyHandlers.ofString() reads the whole body as a String. Then statusCode(), headers().firstValue(...) and body() give the three parts of the response.
Example 5 · Status, headers and body, including a 404
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;import java.io.IOException;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;
/** A stand-in API: a product list with a count header, and a 404 for a missing product. */class ShopApi { static HttpServer start() throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/products", exchange -> { if (exchange.getRequestURI().getPath().equals("/api/v1/products")) { exchange.getResponseHeaders().set("X-Total-Count", "15"); reply(exchange, 200, "application/json", "[{\"id\":9,\"name\":\"Clean Code\"},{\"id\":11,\"name\":\"Atomic Habits\"}]"); } else { reply(exchange, 404, "application/problem+json", "{\"title\":\"Not Found\",\"status\":404,\"detail\":\"No product with id 99\"}"); } }); server.start(); return server; }
static void reply(HttpExchange exchange, int status, String type, String json) throws IOException { byte[] body = json.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", type); exchange.sendResponseHeaders(status, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }}
public class ResponsePartsDemo { private static final HttpClient CLIENT = HttpClient.newHttpClient();
static void show(String url) throws IOException, InterruptedException { HttpRequest request = HttpRequest.newBuilder(URI.create(url)).header("Accept", "application/json").build(); HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("GET " + response.uri().getPath()); System.out.println(" status " + response.statusCode()); System.out.println(" content-type " + response.headers().firstValue("content-type").orElse("-")); System.out.println(" total count " + response.headers().firstValue("X-Total-Count").orElse("-")); System.out.println(" body " + response.body()); }
public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = ShopApi.start(); String baseUrl = "http://127.0.0.1:" + server.getAddress().getPort(); try { show(baseUrl + "/api/v1/products"); show(baseUrl + "/api/v1/products/99"); System.out.println("No exception for the 404: send() returned normally."); } finally { server.stop(0); } }}GET /api/v1/products
status 200
content-type application/json
total count 15
body [{"id":9,"name":"Clean Code"},{"id":11,"name":"Atomic Habits"}]
GET /api/v1/products/99
status 404
content-type application/problem+json
total count -
body {"title":"Not Found","status":404,"detail":"No product with id 99"}
No exception for the 404: send() returned normally.What this code does
firstValuereturns anOptional, soorElse("-")handles a header that is missing, likeX-Total-Counton the 404 response.content-typein lower case still findsContent-Type.- Product 99 does not exist, yet
sendreturned normally with status404and an error body. Only the status code tells you the call failed.
ofString() decodes the body with the charset from Content-Type (UTF-8 when none is given), and firstValue returns an Optional<String>. The most important rule: send does not throw for 404 or 500. The body of an error response usually holds an error message in JSON, so your code must look at statusCode() before it trusts the body. The Timeouts and status codes lesson turns this check into a habit.
Other body handlers:
ofLines(): aStream<String>of lines, for CSV or log-style text.ofFile(Path): saves the body to a file, for downloads.discarding(): ignores the body, when only the status matters (for example204 No Content).
Predict the output
What does send do on a 404?
Read the code and pick what it prints.
Round 1 of 2
The server has no product 99 and answers 404. What happens?
sendAsync and CompletableFuture
A CompletableFuture is a box that will hold a result later. sendAsync returns one at once; thenApply(...) adds the next step and join() waits for the value.
Use client.sendAsync(request, handler) when one screen needs several independent calls, such as the stock of three products. All three start together and you wait once.
Example 6 · Three stock lookups with sendAsync
import com.sun.net.httpserver.HttpServer;import java.io.IOException;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.ArrayList;import java.util.List;import java.util.concurrent.CompletableFuture;
/** A stand-in API that answers /api/v1/products/{id}/stock with a small JSON body. */class StockApi { static HttpServer start() throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/products", exchange -> { String id = exchange.getRequestURI().getPath().split("/")[4]; // /api/v1/products/{id}/stock byte[] body = ("{\"productId\":" + id + ",\"stock\":" + (Integer.parseInt(id) * 10) + "}") .getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "application/json"); exchange.sendResponseHeaders(200, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }); server.start(); return server; }}
public class AsyncDemo { private static final HttpClient CLIENT = HttpClient.newHttpClient();
public static void main(String[] args) throws IOException { HttpServer server = StockApi.start(); String baseUrl = "http://127.0.0.1:" + server.getAddress().getPort(); try { List<CompletableFuture<String>> futures = new ArrayList<>(); for (int id = 1; id <= 3; id++) { HttpRequest request = HttpRequest.newBuilder(URI.create(baseUrl + "/api/v1/products/" + id + "/stock")).build(); CompletableFuture<String> body = CLIENT .sendAsync(request, HttpResponse.BodyHandlers.ofString()) // returns at once .thenApply(HttpResponse::body); futures.add(body); } System.out.println("3 requests started; main is free to do other work.");
for (CompletableFuture<String> future : futures) { System.out.println(" " + future.join()); } } finally { server.stop(0); } }}3 requests started; main is free to do other work.
{"productId":1,"stock":10}
{"productId":2,"stock":20}
{"productId":3,"stock":30}What this code does
sendAsyncreturns aCompletableFutureat once, so all three requests are started before main prints its message.thenApply(HttpResponse::body)keeps only the body when each response arrives.join()waits for each result; looping over the list in order keeps the output in a fixed order even if the answers arrive in a different order.
With send the three calls would run one after another; with sendAsync they all start together. Errors do not throw at sendAsync; they come out of join() wrapped in a CompletionException, whose getCause() is the real IOException. The Concurrency section explains CompletableFuture in full.
send. It is simpler to read, test and debug. Reach for sendAsync only when calls are independent and waiting for them one by one is too slow.Next step
Check your understanding
12 quick questions