What are the different Http/2 Client classes in Java 9?

Http/2 is the newer version of the Http protocol. The improvements of Http/2 include focusing on how data is framed and transported between server and client. In this new version of the Http/2 protocol, separate classes have defined for the Http client, requests, and responses. The new API makes Http connections more easily maintained, faster, and allows for a more responsive application without the need for third-party libraries.

The new API handles HTTP connections through three classes.

  • HttpClient: It handles the creation and sending of requests.
  • HttpRequest: It is used to construct a request to be sent via the HttpClient.
  • HttpResponse: It holds the response from the request that has been sent.

In the below code snippet, we need to send a request to a specific URL and receive the response.

// Create an HttpClient object   
   HttpClient httpClient = HttpClient.newHttpClient();

// Build a HTTPRequest
   HttpRequest httpRequest = HttpRequest.newBuilder().uri(new  URI("https://www.tutorialspoint.com/")).GET().build(); // create a GET request for the given URI
   Map<String, List<String>> headers = httpRequest.headers().map();
   headers.forEach((k, v) -> System.out.println(k + "-" + v));

// Send the request
   HttpResponse httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandler.asString());

// Output the body of the response
   System.out.println("Response: " + httpResponse.body());

Updated on: 25-Mar-2020


Kickstart Your Career

Get certified by completing the course

Get Started