HTTP/2 Client feature of Java 9 with Example

HTTP/2 Client: HTTP/2 client is one of the feature of JDK 9. HTTP/2 is the newest version of the HTTP Protocol. By the help of HTTP/2 client, from the Java application, we can send the HTTP request and we can process the HTTP response. Before JDK 9, To send HTTP request and to process the HTTP response we are using HttpURLConnection class. Now you will wonder why HTTP/2 client is introduced in JDK 9 when we have HttpURLConnection to solve the purpose. But the existing HttpURLConnection has few problems that are eliminated in HTTP/2 client.

Few major problems with HttpURLConnection :

  1. HttpURLConnection class supports only HTTP/1.1 protocol but not HTTP/2.0 protocol. A protocol is nothing but a set of rules or procedures for transmitting data between electronic devices, such as computers. HTTP stands for HyperText Transfer Protocol and here Protocol stands for data communication protocol used to establish communication between client and server. As HttpURLConnection class only support HTTP/1.1 that’s why If we use HttpURLConnection class then we can send only one request per TCP connection. This will cause network traffic and performance issue for the application. As HttpURLConnection supports only HTTP/1.1, It can process only text data not the binary data.
  2. HttpURLConnection class only works in Synchronous mode. Synchronous mode means we have to wait for the request to finish its task before sending another request. If we use HttpURLConnection class to process HTTP requests then we have to sit idle until we get the response of the request then we can process another HTTP request, which will cause performance issue.

Advantages of HTTP/2.0 client:



  1. HTTP/2.0 client is very lightweight and easy to use. HTTP/2.0 client supports both HTTP/1.1 and HTTP/2.0 . HTTP/2 focuses on how data is framed and transported between server and client. In HTTP/1.1, we cannot have more than six connections open at a time, so every request has to wait for the others to complete. The solution of the above problem is multiplexing in HTTP/2 client. This means by the help of HTTP/2 can send multiple HTTP requests in parallel over a single TCP connection.
  2. In HTTP/1.1, When we send one HTTP request which contains the header’s information then HTTP/1.1 consider headers data as additional data, which increases bandwidth. This can be eliminated in HTTP/2.0 by using HPack for header compression.
  3. HTTP/2.0 client supports both Text and Binary data for processing.
  4. HTTP/2.0 client works in both Synchronous and Asynchronous mode.. HTTP/2.0 client gives much better performance when compared with HttpURLConnection.

HTTP API in Java 9: In Java 9 a new API been introduced that is easy to use and which also adds support for HTTP/2. There are 3 new classes introduced to handle HTTP communication.These three classes are present inside jdk.incubator.httpclient module and jdk.incubator.http package inside the module. As jdk.incubator.httpclient is not present inside java application, we have to import it explicitly inside module-info.java file.

  1. HttpClient: HttpClient is a container for configuration information common to multiple HttpRequests. All requests are sent through a HttpClient. HttpClients are immutable and created from a builder returned from newBuilder(). Request builders are created by calling HttpRequest.newBuilder().
  2. HttpRequest:HttpRequest represents one HTTP request which can be sent to a server.HTTP requests are built from HttpRequest builders. HttpRequest builders are obtained by calling HttpRequest.newBuilder. A request’s URI, headers and body can be set. Request bodies are provided through an HttpRequest. BodyProcessor object supplied to the DELETE, POST or PUT methods. GET does not take a body. Once all required parameters have been set in the builder, HttpRequest.Builder.build() is called to return the HttpRequest.
  3. HttpResponse: A HttpResponse is available when the response status code and headers have been received, and typically after the response body has also been received.

Example:

Dummy project of HTTP/2.0: As we already know that we can not use internal APIs directly in Java 9, We have to create an entry in the module descriptor file. Here to use new HTTP API which is present inside jdk.incubator.httpclient module. We have to mention it inside the module descriptor file. We have to follow the below steps to perform an operation using HTTP/2 on Java 9:-

  • First create one folder with name src i.e. the source folder of our java program and inside that one folder with the name geeks, which will contain the meta-data information and create one more folder inside geeks with name httpPackage, which is nothing but the name of the package where we will place our java code.
  • Create module-info.java directly inside geeks just like below:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    module geeks
    {
        requires jdk.incubator.httpclient;
    }

    chevron_right

    
    

  • Create the java class inside httpPackage folder with name Geeksforgeeks.java and with the implementation like below:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    package httpPackage;
    import java.io.IOException;
    import java.net.URI;
    import jdk.incubator.http.HttpClient;
    import jdk.incubator.http.HttpRequest;
    import jdk.incubator.http.HttpResponse;
      
    public class Geeksforgeeks {
        public static void main(String[] args)
        {
            try {
                // Create a HttpClient
                HttpClient httpClient
                    = HttpClient.newHttpClient();
      
                // create a HttpRequest object with the URL
                HttpRequest httpRequest
                    = HttpRequest
                          .newBuilder()
                          .uri(new URI("https:// www.geeksforgeeks.org/about/"))
                          .GET()
                          .build();
                // Synchronous send() method
                // to process the HTTP request.
                // HttpResponse.BodyHandler.asString() handles
                // the body of the response as a String.
                HttpResponse<String> httpResponse
                    = httpClient.send(
                        httpRequest,
                        HttpResponse.BodyHandler.asString());
      
                // statusCode() returns the status code
                // for this response.
                System.out.println(
                    "Status of operation performed:"
                    + httpResponse.statusCode());
            }
            catch (Exception e) {
                System.out.println("Exception" + e);
            }
        }
    }

    chevron_right

    
    

  • To compile our java code, we have to go to src folder and execute below command:
    javac --module-source-path src-d-out -m geeks
  • To run our java code, we have to execute below command:
    java --module-path out -m geeks/httpPackage.Geeksforgeeks

    Output:

    WARNING: using incubator modules jdk.incubator.httpclient
    Status of operation performed:200
    
  • From the above program, we can send one HTTP GET request through synchronous send() method and handle the response as String. Suppose we don’t want to wait until the completion of the HTTP request and want to send another HTTP request in parallel and also we want to save the response into one file. In the above example, we are using the synchronous feature which will block until it has completed. We can make it asynchronous as well as we can save the response into the file.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import java.nio.file.Paths;
    import java.io.IOException;
    import java.net.URI;
    import jdk.incubator.http.HttpClient;
    import jdk.incubator.http.HttpRequest;
    import jdk.incubator.http.HttpResponse;
      
    public class Geeksforgeeks {
        public static void main(String[] args)
        {
            try {
                // Create a HttpClient
                HttpClient httpClient
                    = HttpClient.newHttpClient();
      
                // create a HttpRequest object with the URL
                HttpRequest httpRequest
                    = HttpRequest
                          .newBuilder()
                          .uri(new URI("https:// www.geeksforgeeks.org/about/"))
                          .GET()
                          .build();
      
                // Synchronous send() method
                // to process the HTTP request.
                // HttpResponse.BodyHandler.asFile(Paths.get("GFG.html"))
                // save the response body into GFG.html file
                HttpResponse<String> httpResponse
                    = httpClient.send(
                        httpRequest,
                        HttpResponse.BodyHandler.asFile(Paths.get("GFG.html")));
      
                // statusCode() returns the status code for this response.
                System.out.println(
                    "Status of operation performed:"
                    + httpResponse.statusCode());
      
                // body() returns the response of HTTP request
                System.out.println("Response body:"
                                   + httpResponse.body());
            }
            catch (Exception e) {
                System.out.println("Exception" + e);
            }
        }
    }

    chevron_right

    
    

    Output:

    WARNING: using incubator modules jdk.incubator.httpclient
    Status of operation performed:200
    Response body: It will return the source code of https://www.geeksforgeeks.org/about/ page. As the response is too big i am not adding in it here.
    


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.