Sub topic 7
Reading the status code, headers and body
This chapter assumes you can already build an HttpClient and an HttpRequest and call send. It also assumes you know what HTTP status codes and headers are. Here you will work with the HttpResponse object that send returns.
What an HttpResponse holds
HttpResponse<T> is a read-only object. The type parameter T is the type of the body, and the BodyHandler you passed to send decides it. BodyHandlers.ofString() gives HttpResponse<String>, ofByteArray() gives HttpResponse<byte[]>, and ofFile(path) gives HttpResponse<Path>.
| Method | Returns | Meaning |
|---|---|---|
| `statusCode()` | `int` | The HTTP status, such as 200 or 404 |
| `headers()` | `HttpHeaders` | The response headers |
| `body()` | `T` | The body, converted by the BodyHandler |
| `uri()` | `URI` | The URI that produced this response, which may differ from the request URI after a redirect |
| `version()` | `HttpClient.Version` | `HTTP_1_1` or `HTTP_2` |
| `request()` | `HttpRequest` | The request that was sent |
| `previousResponse()` | `Optional<HttpResponse<T>>` | The earlier response in a redirect chain, if any |
The handler receives the status code and headers before it sees any body bytes. That is how ofString() can read the charset from Content-Type before it decodes the body.
Reading the status code
statusCode() returns a plain int. The client does not throw for 4xx or 5xx statuses, so you must check the value yourself. The next chapter covers failure handling in full. For now, branch on the status before you use the body.
int status = response.statusCode();
boolean ok = status >= 200 && status < 300;Decide what each range means for your application. A 204 has no body, so a String body will be "". A 304 only appears if you sent conditional headers yourself, because the client has no cache.
Reading headers
HttpHeaders is immutable. Its lookups ignore case, so "content-type" and "Content-Type" find the same header. This matters because HTTP/2 sends header names in lowercase.
HttpHeaders headers = response.headers();
Optional<String> type = headers.firstValue("Content-Type");
List<String> cookies = headers.allValues("Set-Cookie");
long length = headers.firstValueAsLong("Content-Length").orElse(-1L);Each method fits a different case:
firstValue(name)returns anOptional<String>. It is empty if the header is absent.allValues(name)returns aList<String>. It is empty if the header is absent, nevernull.firstValueAsLong(name)parses the first value as along. It throwsNumberFormatExceptionif the value is not numeric.map()returns an unmodifiableMap<String, List<String>>of every header, which is useful for logging.
Some headers can repeat, and Set-Cookie is the usual example. Use allValues for these, because firstValue drops all but the first. Do not split a header value on commas yourself unless the header's specification says that is safe. Set-Cookie and dates both contain commas that do not separate values.
A header's absence is normal. A server using chunked transfer encoding sends no Content-Length, so always handle the empty Optional.
Reading the body
body() returns whatever the handler produced. With ofString(), the client decodes the bytes using the charset in Content-Type and falls back to UTF-8 when none is given. If a server sends text in another encoding without declaring it, you get garbled characters. Pass an explicit charset to fix that:
HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString(StandardCharsets.ISO_8859_1));Other handlers fit other jobs. ofByteArray() suits images and other binary data. ofLines() gives a Stream<String> for line-oriented data. discarding() throws the body away and makes body() return null, which suits HEAD requests or calls where only the status matters.
A complete example
This program sends a GET request, checks the status, and prints the headers and body in a defensive order.
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Optional;
public class ReadResponse {
public static void main(String[] args) throws IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/"))
.timeout(Duration.ofSeconds(10))
.GET()
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode());
System.out.println("Version: " + response.version());
System.out.println("URI: " + response.uri());
HttpHeaders headers = response.headers();
Optional<String> type = headers.firstValue("content-type");
System.out.println("Type: " + type.orElse("(none)"));
System.out.println("Length: " + headers.firstValueAsLong("content-length").orElse(-1L));
headers.map().forEach((name, values) ->
System.out.println(" " + name + ": " + String.join(", ", values)));
if (response.statusCode() == 200) {
String body = response.body();
System.out.println("Body has " + body.length() + " characters");
}
}
}The firstValue("content-type") call finds Content-Type because lookups ignore case. Output varies by server, but the status line prints Status: 200 for this site.
Common mistakes
- Treating
body()as lazy. WithofString()andofByteArray(), the whole body is already in memory whensendreturns. A very large response can exhaust the heap. UseofFileorofInputStreamfor those, as a later chapter shows. - Reading headers with the wrong assumption about case. Never iterate
map()looking for an exact-case key. UsefirstValue, which ignores case. - Expecting
nullfor a missing header.firstValuereturns an emptyOptional, andallValuesreturns an empty list. - Expecting the original URI. After redirects,
response.uri()is the final location. UsepreviousResponse()to walk back through the chain. - Forgetting
body()can benull. This happens withdiscarding(), so do not call methods on it.
Reading a header to decide what to do
Headers often drive the next step. This method returns the number of seconds to wait when a server sends Retry-After with a 429 or 503 response.
static Optional<Long> retryAfterSeconds(HttpResponse<?> response) {
int status = response.statusCode();
if (status != 429 && status != 503) {
return Optional.empty();
}
return response.headers().firstValue("Retry-After").flatMap(value -> {
try {
return Optional.of(Long.parseLong(value.trim()));
} catch (NumberFormatException e) {
return Optional.empty(); // value may be an HTTP date, which this method skips
}
});
}The parameter type HttpResponse<?> accepts a response with any body type, since the method never reads the body.
Exercise
A server returns status 200 and a body, but response.headers().firstValueAsLong("Content-Length") returns an empty Optional. Is this an error, and how should the code treat it?
Show answer
It is not an error. The server probably used chunked transfer encoding, or the response was compressed or streamed, so no Content-Length header was sent. The code must treat the length as unknown, for example with orElse(-1L), and read the body without relying on that header.
Exercise
You send a request with BodyHandlers.discarding() and then call response.body().length(). What happens, and what should you use instead?
Show answer
It throws a NullPointerException, because discarding() makes body() return null. Use response.statusCode() and response.headers() for information from a discarded response, or choose ofString() if you need the body.