Java 11's java.net.http.HttpClient
does not seem to check the HTTP status code, except for redirects (if enabled). And all examples found in the wiki and in the Java API documentation always assume that HTTP requests are successful, i.e. they never seem to check the status code of the response.
This is most likely never the desired behavior because an error page from an HTTP 500 (server error) response has probably a different, or no format and can therefore not be handled by the application.
Where should the check for the HTTP status code occur?
The documentation of HttpResponse.BodyHandler
contains the following example snippet:
BodyHandler<Path> bodyHandler = (rspInfo) -> rspInfo.statusCode() == 200
? BodySubscribers.ofFile(Paths.get("/tmp/f"))
: BodySubscribers.replacing(Paths.get("/NULL"));
However, then you would have to check twice for the status code, once in the BodyHandler
shown above, and once when handling the response (since trying to read the body from "/NULL"
would fail).
To me it seems most reasonable to perform the HTTP status code check in the BodyHandler
only, e.g.:
BodyHandler<Path> bodyHandler = (rspInfo) -> {
if (rspInfo.statusCode() == 200) {
return BodySubscribers.ofFile(Paths.get("/tmp/f"));
} else {
throw new RuntimeException("Request failed");
}
};
However, the BodyHandler
documentation does not mention whether it is allowed to throw exceptions, or how HttpClient
would behave in that case.
It is also surprises me that the JDK does not seem to offer functionality for handling unsuccessful HTTP responses out of the box, or am I overlooking something?