Summary
GETs are the most common HTTP request. There should be a simple way to create a GET HttpRequest in one call.
Problem
Four boilerplate method calls are currently required to create a simple GET HttpRequest.
Solution
Add a GET method to HttpRequest which bypasses the builder and returns a HttpRequest directly. A corresponding method is also being added to HttpResponse which returns the body conditionally. This allows code to avoid checking the HttpResponse status code in traditional "if this then that" style and use a more fluent approach (as shown in the example in the spec)
Specification
change to class spec for java.net.http.HttpRequest
@@ -61,29 +61,41 @@
* Once all required parameters have been set in the builder, {@link
* Builder#build() build} will return the {@code HttpRequest}. Builders can be
* copied and modified many times in order to build multiple related requests
* that differ in some parameters.
*
- * <p> The following is an example of a GET request that prints the response
- * body as a String:
- *
+ * <p> The following is an example of an asynchronous POST:
* {@snippet :
* HttpClient client = HttpClient.newHttpClient();
*
* HttpRequest request = HttpRequest.newBuilder()
* .uri(URI.create("http://foo.com/"))
+ * .POST(BodyPublishers.ofString("request body text"))
* .build();
*
* client.sendAsync(request, BodyHandlers.ofString())
* .thenApply(HttpResponse::body)
* .thenAccept(System.out::println)
- * .join(); }
+ * .join();
+ * }
*
* <p>The class {@link BodyPublishers BodyPublishers} provides implementations
* of many common publishers. Alternatively, a custom {@code BodyPublisher}
* implementation can be used.
*
+ * <p> The builder can be avoided for simple GET requests as the following example
+ * shows:
+ * {@snippet :
+ * HttpClient client = HttpClient.newHttpClient();
+ *
+ * HttpRequest request = HttpRequest.GET("https://www.foo.com/");
+ * String response = client.send(request, BodyHandlers.ofString())
+ * .bodyWhen(r -> r.statusCode() == 200)
+ * .orElse("ERROR");
+ * System.out.println(response);
+ * }
+ *
* @since 11
*/
Add the following method to java.net.HttpRequest
+ /**
+ * Convenience method which returns a GET HttpRequest for the given URI string.
+ *
+ * @param uristring the URI string to get
+ * @return a HttpRequest
+ * @throws IllegalArgumentException if the URI scheme is not supported
+ * or if the provided {@code uristring} is not a valid URI.
+ */
+ public static HttpRequest GET(String uristring) {}
Add the following method to java.net.http.HttpResponse
+ /**
+ * Returns the body if the given predicate is satisfied.
+ *
+ * @param predicate the Predicate to test
+ * @return an Optional containing the response body if the predicate returns true
+ */
+ public Optional<T> bodyWhen(Predicate<ResponseInfo> predicate) throws IOException;
+
- csr of
-
JDK-8327796 Add method to java.net.http.HttpRequest to return a GET request in one call
-
- Open
-