Sub topic 6
Reading the Status Code, Headers and Body
This chapter assumes you understand Java 11 syntax, basic HTTP methods and status codes, and checked exceptions. It focuses on reading an HttpResponse after a request succeeds at the network level.
The three parts of a response
An HttpResponse<T> contains:
- A status code, such as
200,404, or500. - Headers, which are metadata such as content type and cache rules.
- A body, whose Java type is chosen by the body handler.
The type parameter T describes the body. For example, HttpResponse<String> contains text, while HttpResponse<byte[]> contains raw bytes.
Check the status code
HttpClient.send does not throw an exception merely because the server returns 404 or 500. Those are valid HTTP responses. Your code must inspect the status.
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 {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://example.com/"))
.header("Accept", "text/html")
.GET()
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
int status = response.statusCode();
System.out.println("Status: " + status);
System.out.println("Content-Type: "
+ response.headers().firstValue("Content-Type").orElse("missing"));
if (status >= 200 && status < 300) {
System.out.println(response.body());
} else {
System.err.println("Server returned HTTP " + status);
}
}
}The 2xx range usually means success. A 3xx status indicates redirection, 4xx usually indicates a client or request problem, and 5xx indicates a server problem. These ranges are conventions, so an API can define more specific meanings.
Read headers safely
response.headers() returns an HttpHeaders object. Header names are case-insensitive, and one name can have multiple values.
| Operation | Result |
|---|---|
| `firstValue("Content-Type")` | An `Optional<String>` containing the first value |
| `allValues("Set-Cookie")` | A list containing every value |
| `map()` | An unmodifiable map of header names to value lists |
Use firstValue when a header should have one meaningful value. Call orElse or orElseThrow so missing headers are handled explicitly.
Choose the body type
BodyHandlers.ofString() collects the response into memory as a String. It is convenient for small text or JSON responses. For binary data, use ofByteArray(). For a large download, use ofFile() so the complete body does not remain in memory.
The body handler runs while the response is received, so choose it before calling send.
Exercise
Does HttpClient.send throw an exception when the server returns HTTP 404?
Show answer
No. It returns an HttpResponse, so the program must inspect statusCode() and handle the non-2xx result itself.