Home » Java » Core Java » Java 11: New HTTP Client API

About Fahd Shariff

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.

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.

(+1 rating, 1 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply

avatar

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

  Subscribe  
Notify of