In Java 11, the incubated HTTP Client API first introduced in Java 9, has been standardised. It makes it easier to connect to a URL, manage request parameters, cookies and sessions, and even supports asynchronous requests and websockets.
To recap, this is how you would read from a URL using the traditional URLConnection approach:
var url = new URL("http://www.google.com");
var conn = url.openConnection();
try (var in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
in.lines().forEach(System.out::println);
}Here is how you can use HttpClient instead:
var httpClient = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder(URI.create("http://www.google.com")).build();
var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());The HTTP Client API also supports asynchonous requests via the sendAsync method which returns a CompletableFuture, as shown below. This means that the thread executing the request doesnβt have to wait for the I/O to complete and can be used to run other tasks.
var httpClient = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder(URI.create("http://www.google.com")).build();
httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);Itβs also very easy to make a POST request containing JSON from a file:
var httpClient = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder(URI.create("http://www.google.com"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofFile(Paths.get("data.json")))
.build();| Published on Java Code Geeks with permission by Fahd Shariff, partner at our JCG program. See the original article here: Java 11: New HTTP Client API Opinions expressed by Java Code Geeks contributors are their own. |
Thank you!
We will contact you soon.
Fahd ShariffDecember 28th, 2018Last Updated: December 24th, 2018

This site uses Akismet to reduce spam. Learn how your comment data is processed.