Sunday, December 23, 2018

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();

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.