This topic is about Java 11 – Standard HttpClient.
An enhanced HttpClient API was introduced in Java 9 as an experimental feature. With Java 11, now HttpClient is a standard. It is recommended to use instead of other HTTP Client APIs like Apache Http Client API. It is quite feature rich and now Java based applications can make HTTP requests without using any external dependency.
Steps
Following are the steps to use an HttpClient.
- Create HttpClient instance using HttpClient.newBuilder() instance
- Create HttpRequest instance using HttpRequest.newBuilder() instance
- Make a request using httpClient.send() and get a response object.
Example
import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; public class APITester { public static void main(String[] args) { HttpClient httpClient = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .connectTimeout(Duration.ofSeconds(10)) .build(); try { HttpRequest request = HttpRequest.newBuilder() .GET() .uri(URI.create("https://www.google.com")) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Status code: " + response.statusCode()); System.out.println("Headers: " + response.headers().allValues("content-type")); System.out.println("Body: " + response.body()); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
Output
It will print the following output.
Status code: 200 Headers: [text/html; charset=ISO-8859-1] Body: <!doctype html> ... </html>
To learn more, Click Here.
Pingback: Java 11 - Environment Setup - Adglob Infosystem Pvt Ltd