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:
1 2 3 4 5 | 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:
1 2 3 4 | var httpClient = HttpClient.newHttpClient(); 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.
1 2 3 4 5 | var httpClient = HttpClient.newHttpClient(); 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:
1 2 3 4 5 | var httpClient = HttpClient.newHttpClient(); .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. |