Java HTTP Responses
A Java HTTP response is the HttpResponse object that HttpClient.send() returns after a server answers your request. It holds the status code, the response headers, the body and some details about the exchange, such as the final URI and the HTTP version.
Reading a response well means more than calling body(). In this lesson you will read status codes and headers, follow redirects, choose the right body handler, handle responses asynchronously and convert a body straight into a Java object. The lesson ends with a reusable response handler that retries busy servers and reports errors clearly.
What a Java HTTP Response Contains
HttpResponse<T> is a generic interface. The type T is the type of the body, and it is decided by the body handler you pass to send(): BodyHandlers.ofString() gives an HttpResponse<String>, BodyHandlers.ofByteArray() gives an HttpResponse<byte[]>, and so on.
| Method | Returns |
|---|---|
statusCode() | The HTTP status code, such as 200 or 404 |
body() | The body, converted by the body handler |
headers() | An HttpHeaders object with all response headers |
uri() | The URI of the response (after any redirects) |
version() | The HTTP version used: HTTP_1_1 or HTTP_2 |
request() | The HttpRequest that produced this response |
previousResponse() | The earlier response in a redirect chain, if any |
sslSession() | TLS details for HTTPS responses, if any |
Note: An
HttpResponseis immutable. Once you have it, nothing about it changes, so it is safe to pass between threads.
A Local Server for the Examples
All examples talk to a small server on http://localhost:8092, so they run offline. Save it as ShopServer.java next to the examples. Each path returns a different kind of response:
/products/1returns200with a JSON product./products/99returns404 Not Found./old-productsreturns a301redirect to/products/1./report.csvreturns a small CSV file./flakyreturns503 Service Unavailabletwice, then200.
// FILE: ShopServer.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.concurrent.atomic.AtomicInteger;
// A small local HTTP server on http://localhost:8092 used by the examples
public class ShopServer {
private static final AtomicInteger FLAKY_CALLS = new AtomicInteger();
public static HttpServer start() throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 8092), 0);
server.createContext("/products/1", ex -> send(ex, 200, "application/json",
"{\"id\":1,\"name\":\"Keyboard\",\"price\":1499}"));
server.createContext("/products/99", ex -> send(ex, 404, "application/json",
"{\"error\":\"product 99 not found\"}"));
server.createContext("/old-products", ex -> { // permanent redirect
ex.getResponseHeaders().add("Location", "/products/1");
send(ex, 301, "text/plain", "");
});
server.createContext("/report.csv", ex -> send(ex, 200, "text/csv",
"day,orders\nMon,12\nTue,19\nWed,7\n"));
server.createContext("/flaky", ex -> { // fails twice, then works
if (FLAKY_CALLS.incrementAndGet() <= 2) {
ex.getResponseHeaders().add("Retry-After", "1");
send(ex, 503, "application/json", "{\"error\":\"busy\"}");
} else {
send(ex, 200, "application/json", "{\"status\":\"ok\"}");
}
});
server.start();
return server;
}
private static void send(HttpExchange ex, int status, String type, String text) throws IOException {
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().add("Content-Type", type);
ex.getResponseHeaders().add("Cache-Control", "max-age=60");
ex.getResponseHeaders().add("Set-Cookie", "session=abc123");
ex.getResponseHeaders().add("Set-Cookie", "theme=dark");
ex.sendResponseHeaders(status, bytes.length == 0 ? -1 : bytes.length);
if (bytes.length > 0) ex.getResponseBody().write(bytes);
ex.close();
}
}
The server uses the JDK's built-in com.sun.net.httpserver package, so you need nothing beyond a JDK 21 or newer.
Reading the Status, Body and Details
The simplest use of a response is to read its status code and body as text. The other methods tell you where the response came from and how it was delivered.
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 = ShopServer.start();
try (HttpClient client = HttpClient.newHttpClient()) {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8092/products/1")).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode());
System.out.println("Body: " + response.body());
System.out.println("URI: " + response.uri());
System.out.println("Version: " + response.version());
System.out.println("Method: " + response.request().method());
} finally {
server.stop(0);
}
}
}
Output:
Status: 200
Body: {"id":1,"name":"Keyboard","price":1499}
URI: http://localhost:8092/products/1
Version: HTTP_1_1
Method: GET
How it works:
BodyHandlers.ofString()reads the whole body and decodes it using the charset from theContent-Typeheader (UTF-8 if none is given).version()isHTTP_1_1because the local server does not speak HTTP/2. Against most public HTTPS sites the same client would reportHTTP_2.request()returns the request that was sent, which is handy when you log many responses at once.
Reading Response Headers
headers() returns an HttpHeaders object. Header names are case-insensitive, and one header can have several values, so the class offers a few ways to read them.
HttpHeaders method | Returns |
|---|---|
firstValue(name) | Optional<String> with the first value |
firstValueAsLong(name) | OptionalLong, for numeric headers |
allValues(name) | List<String> with every value |
map() | Map<String, List<String>> with all headers |
import com.sun.net.httpserver.HttpServer;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ResponseHeaders {
public static void main(String[] args) throws Exception {
HttpServer server = ShopServer.start();
try (HttpClient client = HttpClient.newHttpClient()) {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8092/products/1")).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
HttpHeaders headers = response.headers();
// Header names are case-insensitive
System.out.println("Content-Type: " + headers.firstValue("content-type").orElse("unknown"));
System.out.println("Content-Length: " + headers.firstValueAsLong("Content-Length").orElse(-1));
System.out.println("Cookies: " + headers.allValues("Set-Cookie"));
System.out.println("ETag present? " + headers.firstValue("ETag").isPresent());
System.out.println("All names: " + headers.map().keySet());
} finally {
server.stop(0);
}
}
}
Output:
Content-Type: application/json
Content-Length: 39
Cookies: [session=abc123, theme=dark]
ETag present? false
All names: [cache-control, content-length, content-type, date, set-cookie]
How it works:
firstValue("content-type")finds theContent-Typeheader even though the case differs.allValues("Set-Cookie")returns both cookies;firstValue()would return only the first one.- A missing header gives an empty
Optional, soorElse()orisPresent()avoids aNullPointerException. - The server added
dateandcontent-lengthon its own, which is why they appear inmap().
Handling HTTP Status Codes in Java
The client does not throw an exception for 404 or 500. Any response the server sends counts as a successful exchange, so your code must check statusCode() itself. Status codes fall into five classes.
| Range | Class | Common examples |
|---|---|---|
| 1xx | Informational | 100 Continue |
| 2xx | Success | 200 OK, 201 Created, 204 No Content |
| 3xx | Redirect | 301 Moved Permanently, 302 Found, 304 Not Modified |
| 4xx | Client error | 400 Bad Request, 401 Unauthorized, 404 Not Found |
| 5xx | Server error | 500 Internal Server Error, 503 Service Unavailable |
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 StatusCodes {
// Group a status code into its class
static String describe(int status) {
return switch (status / 100) {
case 2 -> "success";
case 3 -> "redirect";
case 4 -> "client error";
case 5 -> "server error";
default -> "informational";
};
}
public static void main(String[] args) throws Exception {
HttpServer server = ShopServer.start();
String[] paths = {"/products/1", "/products/99", "/old-products", "/flaky"};
// The default client does NOT follow redirects
try (HttpClient client = HttpClient.newHttpClient()) {
for (String path : paths) {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8092" + path)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int status = response.statusCode();
System.out.printf("%-14s %d %-13s %s%n", path, status, describe(status), response.body());
}
} finally {
server.stop(0);
}
}
}
Output:
/products/1 200 success {"id":1,"name":"Keyboard","price":1499}
/products/99 404 client error {"error":"product 99 not found"}
/old-products 301 redirect
/flaky 503 server error {"error":"busy"}
How it works:
status / 100uses integer division to get the first digit, and theswitchexpression maps it to a class name.- The
404and503responses still have bodies. APIs usually explain the error there, so read the body before giving up. - The
301response is returned as-is, because a client fromHttpClient.newHttpClient()usesRedirect.NEVER.
Following Redirects and previousResponse()
To follow redirects automatically, build the client with followRedirects(). The response you get is then the final one, and previousResponse() lets you see the steps that led to it.
HttpClient.Redirect | Behaviour |
|---|---|
NEVER | Never follow redirects (the default) |
NORMAL | Follow redirects, except from HTTPS to HTTP |
ALWAYS | Always follow redirects |
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 FollowRedirect {
public static void main(String[] args) throws Exception {
HttpServer server = ShopServer.start();
try (HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.build()) {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8092/old-products")).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Final status: " + response.statusCode());
System.out.println("Final URI: " + response.uri());
System.out.println("Body: " + response.body());
// previousResponse() walks back through the redirect chain
response.previousResponse().ifPresent(previous ->
System.out.println("Redirected from " + previous.uri() + " with status "
+ previous.statusCode() + ", Location: "
+ previous.headers().firstValue("Location").orElse("-")));
} finally {
server.stop(0);
}
}
}
Output:
Final status: 200
Final URI: http://localhost:8092/products/1
Body: {"id":1,"name":"Keyboard","price":1499}
Redirected from http://localhost:8092/old-products with status 301, Location: /products/1
How it works:
- The client sees
301withLocation: /products/1, resolves that relative path against the original URI and sends a new request. response.uri()is the final address, not the one you requested. Compare it withrequest().uri()to detect a redirect.previousResponse()returns the301response. Its body is not kept, but its status and headers are.
Note:
NORMALrefuses to follow a redirect from HTTPS to HTTP, which protects you from silently dropping encryption. UseALWAYSonly when you trust every server in the chain.
Choosing a Body Handler
The body handler decides how the bytes of the body are processed: kept in memory, streamed line by line, written to a file or thrown away. Picking the right one saves memory and code.
BodyHandlers method | Body type | Best for |
|---|---|---|
ofString() | String | JSON, HTML and other small text |
ofByteArray() | byte[] | Small binary data, such as images |
ofLines() | Stream<String> | Large text processed line by line |
ofFile(Path) | Path | Downloads saved to disk |
ofInputStream() | InputStream | Streaming into other APIs |
discarding() | Void | When only the status and headers matter |
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.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
public class BodyHandlersDemo {
public static void main(String[] args) throws Exception {
HttpServer server = ShopServer.start();
HttpRequest csv = HttpRequest.newBuilder(URI.create("http://localhost:8092/report.csv")).build();
try (HttpClient client = HttpClient.newHttpClient()) {
// 1. Raw bytes
HttpResponse<byte[]> bytes = client.send(csv, BodyHandlers.ofByteArray());
System.out.println("Bytes received: " + bytes.body().length);
// 2. A lazy stream of lines (skip the header row)
HttpResponse<Stream<String>> lines = client.send(csv, BodyHandlers.ofLines());
try (Stream<String> rows = lines.body()) {
int totalOrders = rows.skip(1)
.mapToInt(row -> Integer.parseInt(row.split(",")[1]))
.sum();
System.out.println("Total orders: " + totalOrders);
}
// 3. Save straight to a file
Path target = Files.createTempFile("report", ".csv");
HttpResponse<Path> saved = client.send(csv, BodyHandlers.ofFile(target));
List<String> fileLines = Files.readAllLines(saved.body());
System.out.println("Saved file has " + fileLines.size() + " lines");
Files.delete(target);
// 4. Ignore the body, keep status and headers
HttpResponse<Void> discarded = client.send(csv, BodyHandlers.discarding());
System.out.println("Discarded body: " + discarded.body() + ", status " + discarded.statusCode());
} finally {
server.stop(0);
}
}
}
Output:
Bytes received: 31
Total orders: 38
Saved file has 4 lines
Discarded body: null, status 200
How it works:
ofByteArray()keeps the exact bytes, with no charset decoding.ofLines()returns a lazyStream<String>. Lines are read as the stream consumes them, so even a huge CSV never sits in memory all at once. Close the stream (here with try-with-resources) to free the connection.ofFile(target)writes the body to disk and returns thePath. This is the right choice for downloads.discarding()reads and drops the body, andbody()returnsnull.
Note:
ofString()andofByteArray()load the entire body into memory. For downloads of unknown size, useofFile(),ofLines()orofInputStream()instead.
Handling Responses Asynchronously
sendAsync() returns a CompletableFuture<HttpResponse<T>> immediately, without waiting for the server. You can start several requests at once and process each response when it arrives.
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 AsyncResponse {
public static void main(String[] args) throws Exception {
HttpServer server = ShopServer.start();
try (HttpClient client = HttpClient.newHttpClient()) {
List<String> paths = List.of("/products/1", "/products/99", "/report.csv");
// Start all requests at once; each future completes with an HttpResponse
List<CompletableFuture<String>> futures = paths.stream()
.map(path -> HttpRequest.newBuilder(URI.create("http://localhost:8092" + path)).build())
.map(request -> client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> response.uri().getPath() + " -> "
+ response.statusCode() + " ("
+ response.body().length() + " chars)"))
.toList();
// join() waits for each result, in the original order
futures.forEach(future -> System.out.println(future.join()));
} finally {
server.stop(0);
}
}
}
Output:
/products/1 -> 200 (39 chars)
/products/99 -> 404 (32 chars)
/report.csv -> 200 (31 chars)
How it works:
toList()forces the stream to run, so all three requests are in flight before the firstjoin().thenApply()turns eachHttpResponseinto a summary line as soon as that response is complete.join()waits for each future in list order, so the output order is stable even if the responses arrive in a different order. Learn more about chaining in Java CompletableFuture.
Converting a Response Body into a Java Object
A body handler can do more than collect text. With BodySubscribers.mapping(), you can convert the body into any type while it is received, so send() returns an HttpResponse<Product> directly.
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.net.http.HttpResponse.BodyHandler;
import java.net.http.HttpResponse.BodySubscribers;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MappedHandler {
record Product(int id, String name, int price) { }
// Turn {"id":1,"name":"Keyboard","price":1499} into a Product (simple demo parser)
static Product parseProduct(String json) {
Matcher m = Pattern.compile("\"id\":(\\d+),\"name\":\"([^\"]*)\",\"price\":(\\d+)").matcher(json);
if (!m.find()) throw new IllegalArgumentException("Not a product: " + json);
return new Product(Integer.parseInt(m.group(1)), m.group(2), Integer.parseInt(m.group(3)));
}
// A body handler that converts the body to a Product while it is received
static BodyHandler<Product> asProduct() {
return responseInfo -> BodySubscribers.mapping(
BodySubscribers.ofString(StandardCharsets.UTF_8),
MappedHandler::parseProduct);
}
public static void main(String[] args) throws Exception {
HttpServer server = ShopServer.start();
try (HttpClient client = HttpClient.newHttpClient()) {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8092/products/1")).build();
HttpResponse<Product> response = client.send(request, asProduct());
Product product = response.body();
System.out.println(product);
System.out.println(product.name() + " costs Rs. " + product.price());
} finally {
server.stop(0);
}
}
}
Output:
Product[id=1, name=Keyboard, price=1499]
Keyboard costs Rs. 1499
How it works:
- A
BodyHandleris a functional interface. It receivesresponseInfo(status and headers) and returns aBodySubscriberthat consumes the body. BodySubscribers.mapping(ofString(...), parseProduct)first collects the body as aString, then passes it toparseProduct.- The
Productrecord gives you typed access withname()andprice().
Note: The regular expression parser only works for this exact JSON shape. In real projects, call a JSON library such as Jackson or Gson inside
mapping(); the handler pattern stays the same.
Real-World Example: A Reusable API Response Handler
Production code usually wraps response handling in one place. This ApiResponseHandler sends a GET request and then decides what to do based on the response:
2xxwith a JSONContent-Typereturns the body.503is retried, waiting for the time given in theRetry-Afterheader.- Anything else becomes an
ApiExceptionthat carries the status code and the server's error message.
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.time.Duration;
public class ApiResponseHandler implements AutoCloseable {
// A failed response, with everything needed to log or report it
static class ApiException extends Exception {
final int status;
ApiException(int status, String message) {
super("HTTP " + status + ": " + message);
this.status = status;
}
}
private final HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(3))
.build();
// GET a URI and return the body, retrying 503 responses
String getBody(String url, int maxAttempts) throws IOException, InterruptedException, ApiException {
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
.header("Accept", "application/json")
.timeout(Duration.ofSeconds(5))
.build();
for (int attempt = 1; ; attempt++) {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int status = response.statusCode();
System.out.printf(" attempt %d -> %d%n", attempt, status);
if (status >= 200 && status < 300) {
String type = response.headers().firstValue("Content-Type").orElse("");
if (!type.startsWith("application/json")) {
throw new ApiException(status, "expected JSON but got " + type);
}
return response.body();
}
if (status == 503 && attempt < maxAttempts) {
long waitSeconds = response.headers().firstValueAsLong("Retry-After").orElse(1);
Thread.sleep(Duration.ofMillis(waitSeconds * 100)); // shortened wait for the demo
continue;
}
throw new ApiException(status, response.body());
}
}
@Override
public void close() {
client.close();
}
public static void main(String[] args) throws Exception {
HttpServer server = ShopServer.start();
String[] urls = {
"http://localhost:8092/old-products", // redirect, then 200
"http://localhost:8092/flaky", // 503, 503, then 200
"http://localhost:8092/products/99", // 404
"http://localhost:8092/report.csv" // 200, but not JSON
};
try (ApiResponseHandler api = new ApiResponseHandler()) {
for (String url : urls) {
System.out.println("GET " + URI.create(url).getPath());
try {
System.out.println(" OK: " + api.getBody(url, 3));
} catch (ApiException e) {
System.out.println(" FAILED: " + e.getMessage());
}
}
} finally {
server.stop(0);
}
}
}
Output:
GET /old-products
attempt 1 -> 200
OK: {"id":1,"name":"Keyboard","price":1499}
GET /flaky
attempt 1 -> 503
attempt 2 -> 503
attempt 3 -> 200
OK: {"status":"ok"}
GET /products/99
attempt 1 -> 404
FAILED: HTTP 404: {"error":"product 99 not found"}
GET /report.csv
attempt 1 -> 200
FAILED: HTTP 200: expected JSON but got text/csv
How it works:
- Redirects are invisible to the caller. The client follows the
301from/old-products, sogetBody()only sees the final200. - Status first, then headers. A
2xxresponse is accepted only if itsContent-Typeis JSON. The CSV report has a successful status but the wrong type, so it is rejected with a clear message instead of failing later in a JSON parser. - Retrying with Retry-After. For
503, the method readsRetry-AfterwithfirstValueAsLong()and waits before trying again. The demo shortens the wait to 100 ms per second; real code would wait the full time. - Errors keep their details. The
404becomes anApiExceptionholding the status and the server's error body, so callers can log it or show it to the user. - One client, closed once. The class implements
AutoCloseable, so try-with-resources closes theHttpClientwhen the work is done.
To learn how the requests in these examples are built, with methods, headers and bodies, see Java HTTP Requests. For client settings such as timeouts, redirects and executors, see the Java HttpClient lesson.