RFR: 8327796: Add method to java.net.http.HttpRequest to return a GET request in one call [v2]
Michael McMahon
michaelm at openjdk.org
Tue Mar 12 16:15:32 UTC 2024
On Tue, 12 Mar 2024 14:43:03 GMT, Michael McMahon <michaelm at openjdk.org> wrote:
>> src/java.net.http/share/classes/java/net/http/HttpRequest.java line 91:
>>
>>> 89: *
>>> 90: * HttpRequest request = HttpRequest.GET("https://www.foo.com/");
>>> 91: * String response = client.send(request, BodyHandlers.ofString()).body();
>>
>> I am not sure whether line 91 is such a good idea. Wouldn't you typically first check whether the status is 200 before handling the response? I wonder if we could extend HttpResponse to make dealing with this easier?
>
> Good point. We could add a method like `bodyWhen(Predicate<ResponseInfo>)` which would return the body if the predicate is satisfied but throws an exception otherwise.
>
> `String response = client.send(request, BodyHandlers.ofString()).bodyWhen(r -> r.statusCode() == 200);`
I've pushed an update for discussion where a new method is added to HttpResponse as follows:
`Optional<T> bodyWhen(Predicate<ResponseInfo> predicate)`
Using Optional is more flexible than explicitly throwing an exception in the method
-------------
PR Review Comment: https://git.openjdk.org/jdk/pull/18227#discussion_r1521754276
More information about the net-dev
mailing list