RFR: 8327796: Add method to java.net.http.HttpRequest to return a GET request in one call

Michael McMahon michaelm at openjdk.org
Tue Mar 12 14:45:13 UTC 2024


On Tue, 12 Mar 2024 13:04:17 GMT, Daniel Fuchs <dfuchs at openjdk.org> wrote:

>> Hi,
>> 
>> This PR proposes to add simple utility method which returns a simple GET HttpRequest in one call. The current builder pattern requires 4 (or 3 since GET is the default method) method calls to achieve the same effect.
>> 
>> Thanks,
>> Michael
>
> 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);`

-------------

PR Review Comment: https://git.openjdk.org/jdk/pull/18227#discussion_r1521596847


More information about the net-dev mailing list