Core Java

Java 11: New HTTP Client API

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.

Fahd Shariff

Fahd is a software engineer working in the financial services industry. He is passionate about technology and specializes in Java application development in distributed environments.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button