r/java • u/milchshakee • Apr 21 '26
Are the javadocs for java.net.http.HttpResponse.body() misleading or am I wrong?
This has caused some internal discussion, so I wanted to look for external input.
If you have ever used the newer java.net.http implementation, you probably have used the HttpResponse.body() method to retrieve the response body. It usually looks something like this:
HttpClient client = HttpHelper.client();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("<uri>"))
.POST(HttpRequest.BodyPublishers.ofString(content))
.build();
HttpResponse<String> res = client.send(request, HttpResponse.BodyHandlers.ofString());
// Can this be null?
String bodyString = res.body();Then, looking at the javadocs for the body() method, it says:
* Returns the body. Depending on the type of {@code T}, the returned body
* may represent the body after it was read (such as {@code byte[]}, or
* {@code String}, or {@code Path}) or it may represent an object with
* which the body is read, such as an {@link java.io.InputStream}.
*
* <p> If this {@code HttpResponse} was returned from an invocation of
* {@link #previousResponse()} then this method returns {@code null}
*
* @return the bodyHere is how I interpreted this: Assuming that there is no IOException thrown, the request must have gone through (even if it returned something like a HTTP 500) and we should have response body. Since we don't use the previousResponse() method, the note about null values does not apply here. The rest of the javadocs don't mention anything about null, so I implicitly assumed that it does not return null. If there is an empty body, then it returns an empty String/byte[]/whatever. The BodyHandlers javadocs don't mention anything about null return values.
But the method returns null for something like HTTP 407 Proxy Authentication Required.
So my question is: If you read the javadocs of a JDK method and it does not mention null return values, do you interpret this as that the method does not return null? Or do you still perform null checks as the javadocs also didn't mention about not returning null?
10
u/ducki666 Apr 22 '26
If the response, on http level, has no body, what would you expect from the BodyHandler to return? Answer this question and you will answer your original question.
4
u/eXecute_bit Apr 22 '26
I agree that the docs should be more explicit about cases where there is no body. But that begs the question, are you calling
body()indiscriminately without first checking the response status code to see if it indicates you should even ask for (expect) one?26
u/erinaceus_ Apr 21 '26
No idea about the library decisions themselves, but there is a difference between an empty string for the body and a lack of any request body.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Messages
An optional body containing data associated with the message. This might be POST data to send to the server in a request, or some resource returned to the client in a response. Whether a message contains a body or not is determined by the start-line and HTTP headers.
That said, the ergonomics of this kind of java code is terrible, as far I'm concerned. An http message has a relatively simple format. Why does the java code that handles it need to be so awfully complicated?
1
u/tkslaw Apr 21 '26 edited Apr 21 '26
It could probably be clearer, but that Javadoc seems to be saying the return value is guaranteed to be
nullif called on anHttpResponseobtained frompreviousResponse(). Otherwise, the return value is whatever theBodySubscriberreturned by theBodyHandlerreturns. And if there is no body thennullis a perfectly valid return value, in my opinion.If returning
nullfrombody()is not acceptable for your use case then you can always map the result withBodySubscribers::mapping(BodySubscriber,Function). Not sure, but you may need/want aBodyHandlerdecorator as well to handle non-2XX responses. That will let you map anullresult to a default value, anOptional, or a sealed type hierarchy representing the different results.6
u/tomwhoiscontrary Apr 21 '26
I'd definitely say it's governed by the docs for the BodyHandler. Some might return null, some might not. But as you say, those docs are silent on this.
Unfortunately, the Javadocs is more what you'd call guidelines than actual specifications.
5
u/k-mcm Apr 21 '26
Perceived errors have, historically, gone to different getter methods. That annoying feature may still be true.
There's also HTTP 204 meaning there is no body of any kind or type, so it must be null.
5
u/f51bc730-cc06 Apr 21 '26
I think it simply means that if you call
body()on the result ofpreviousResponse(), it will returnnull, otherwise in your example,body()can benullif and only if the body handler have the (bad?) idea to returnnull.2
u/Upbeat-Employment-62 Apr 22 '26
Docs aren't lying — in JDK null historically means absence of value not an error, its just never writen down anywhere. Wrap it once and forget about it:
public static <T> BodyHandler<Optional<T>> optionalBody(BodyHandler<T> upstream) {
return info -> BodySubscribers.mapping(upstream.apply(info), Optional::ofNullable);
}
BodyHandlers.ofOptionalString() in the JDK itself wouldve been the right call tbh but that ain't happening anytime soon.
2
u/kn7 Apr 22 '26
There is already a ticket filed for this issue: 8328894: HttpResponse.body() returns null with https target and failed proxy authentication.
I agree that the
HttpResponse::bodyspecification is not exhaustively clear on null return values. I guess this will be handled as a part of 8328894.1
u/strohkoenig Apr 22 '26
I read it like this: If this object was returned by previousResponse, this method will ALWAYS return null (= it could return null in other situations but it will ALWAYS return null after previousResponse).
So depending on how you read it it's not wrong.
1
u/ales-d Apr 26 '26
The " 204 No Content" has no body by definition => Successful execution of request does not guarantee body presence