The Wayback Machine - https://web.archive.org/web/20240922044936/https://www.geeksforgeeks.org/http-2-client-feature-of-java-9-with-example/
Open In App

HTTP/2 Client feature of Java 9 with Example

Last Updated : 22 Jan, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:




    module geeks
    {
        requires jdk.incubator.httpclient;
    }

    
    

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




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

    
    

  • 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.




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

    
    

    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.
    


Similar Reads

Creating a Socket to Display Message to a Single Client in Java
This article describes the basic client-server connection where a client connects, a server sends a message to the client and the client displays the message using a socket connection. A client program sockets establish a connection with the server socket of server application then server socket connects with internal sockets in the server applicat
2 min read
Transfer the File "Client Socket to Server Socket" in Java
Prerequisites: Socket Programming in JavaFile Handling in JavaThis article describes a one-way client and Server Setup where a client connects, and sends the file to the server and the server writes the file in another location with a different name. It means we send the file using the server socket. Socket Programming in JavaSocket Programming is
4 min read
Service Client Module in Java
A Client Module in Java is a set of classes and methods that are used to connect to, interact with, and consume services from a server. It is the front-end component of a client/server architecture. It is typically responsible for initiating communication with the server, sending and receiving data, and interpreting responses from the server. The C
6 min read
Java Spring Boot Microservices - Client Side Load Balancing with Spring Cloud LoadBalancer
Spring Cloud is a collection of projects like load balancing, service discovery, circuit breakers, routing, micro-proxy, etc will be given by Spring Cloud. So spring Cloud basically provides some of the common tools and techniques and projects to quickly develop some common patterns of the microservices. Basically, there are two ways to load balanc
12 min read
Multi-threaded Chat Application in Java | Set 2 (Client Side Programming)
Prerequisites : Introducing threads in socket programming, Multi-threaded chat Application | Set 1 This article gives the implementation of client program for the multi-threaded chat application. Till now all examples in socket programming assume that client first sends some information and then server or other clients responds to that information.
5 min read
Try-with-resources Feature in Java
In Java, the Try-with-resources statement is a try statement that declares one or more resources in it. A resource is an object that must be closed once your program is done using it. For example, a File resource or a Socket connection resource. The try-with-resources statement ensures that each resource is closed at the end of the statement execut
4 min read
How to define a client-side script in HTML5 ?
To define a client-side script in HTML5, we can do &lt;script&gt; tag or adding external script file by src attribute to the HTML file. &lt;script&gt; tag contains the JavaScript to be added for the client-side scripting. Syntax: &lt;script&gt; // JavaScript goes here console.log('GeeksforGeeks'); &lt;/script&gt; Below are the examples for the abov
1 min read
How to create a client-side image-map in HTML5 ?
In this article, we will create a client-side image map by using an &lt;img&gt; tag. The &lt;img&gt; tag is used to add images on a webpage. This tag is an empty tag which means it can contain only a list of attributes and it has no closing tag. Syntax: &lt;img src="url" alt="some_text" usemap="#mapname"&gt; Example: &lt;!DOCTYPE html&gt; &lt;html
1 min read
How to set alternate content for users that do not support client-side scripts ?
In this article, we define an alternate content for users that do not support client-side scripts by using &lt;noscript&gt; tag in the HTML document. It is used to display the text for those browsers that does not support script tag or the browsers disable the script for the user. Syntax: &lt;noscript&gt; Contents... &lt;/noscript&gt; Example: &lt;
1 min read
HTTP status codes | Client Error Responses
The browser and the site server have a conversation in the form of HTTP status codes. The server gives responses to the browser’s request in the form of a three-digit code known as HTTP status codes. The categorization of HTTP status codes is done in five sections which are listed below. Informational responses (100–199)Successful responses (200–29
4 min read
Servlet - Client HTTP Request
When the user wants some information, he/she will request the information through the browser. Then the browser will put a request for a web page to the webserver. It sends the request information to the webserver which cannot be read directly because this information will be part of the header of the HTTP request. Header and DescriptionsHeader Nam
3 min read
What is the mechanism to store the data on the client's browser in HTML ?
Server-side storage stores data on the server (i.e. an external database) and client-side storage allow the user to store data on the client (i.e. user's browser). client-side storage consists of JavaScript APIs that allow you to store data on the client i.e. on the user's machine and then retrieve it when it is needed. This has many different uses
4 min read
Spring Cloud - Client Side Load Balancer
Spring Cloud is a collection of projects like load balancing, service discovery, circuit breakers, routing, micro-proxy, etc will be given by Spring Cloud. So spring Cloud basically provides some of the common tools and techniques and projects to quickly develop some common patterns of the microservices. What is Load Balancer in Spring Cloud? Takin
5 min read
Client Side Service Discovery in Microservices
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
6 min read
Spring Cloud - Difference Between Client Side and Server Side Load Balancer
Spring Cloud is a collection of projects like load balancing, service discovery, circuit breakers, routing, micro-proxy, etc will be given by Spring Cloud. So spring Cloud basically provides some of the common tools and techniques and projects to quickly develop some common patterns of the microservices. What is Load Balancer in Spring Cloud? Takin
3 min read
Keycloak - Create Realm, Client, Roles, and User
Keycloak is Open Source Identity and Access Management (IAM) tool developed by Red Hat. By using this you can add authentication to applications and secure services with minimum effort. No need to deal with storing users or authenticating users. Keycloak provides user federation, strong authentication, user management, fine-grained authorization, a
5 min read
How Eureka Server and Client Communicate with Each Other in Microservices?
Service Discovery is one of the major things of a microservice-based architecture. Eureka is the Netflix Service Discovery Server and Client. The server can be configured and deployed to be highly functional, with each server copying the state of the registered services to the others. In the previous article, we have seen How to Register Microservi
5 min read
Spring Cloud - Client Side Load Balancing with Ribbon
Spring Cloud is a collection of projects like load balancing, service discovery, circuit breakers, routing, micro-proxy, etc will be given by Spring Cloud. So spring Cloud basically provides some of the common tools and techniques and projects to quickly develop some common patterns of the microservices. Basically, there are two ways to load balanc
13 min read
Spring Boot - Admin Client
In Sprint Boot, Admin and Client can be implemented so that the client can be registered with the server, and then the server maintains the client's service health and availability, scales up the service, and also measures the representation of the client. Spring Boot Admin ServerThe Admin Server can represent the UI dashboard of the Spring Boot ap
4 min read
How to add Rate the App feature in Android
When you publish your app on google play store it is important to get feedback from the user. Unless the user does not love or hate your app, they are not likely to go out of their way to rate your app. Since high rating indicates the success of your app, and even criticism is required to make the application better. So, it is better to add a rate
2 min read
How to Add YouTube Live Stream Feature in Android?
YouTube provides a service to make a live stream video on their platform to connect with your subscribers. In this article, we will take a look at the implementation of YouTube video live streaming video in Android App. What we are going to build in this article? We will be building a simple application in which we will be displaying a simple butto
4 min read
How to Add Drag And Drop Feature in Android RecyclerView?
Drag And Drop feature is very helpful. It is very simple and easy to implement. It is used in many apps that are famous, and if we're doing some project it is very convenient to implement it. You should know the RecyclerAdapter Class. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://med
4 min read
How to design Bootstrap Fullscreen Select feature for Mobiles ?
In this article, we will learn how to design Bootstrap fullscreen select feature for mobile devices. It provides advanced HTML full screen select functionality.It provides in and out animations.It provides open and close events function callbacks.It provides CSS3 animated buttons, dropdowns and texts.Please download the required pre-compiled librar
3 min read
How to load more feature using jQuery ?
Bootstrap provides a lot of useful features that we generally integrate into our websites. One of them is the "Load More" feature which we can see on every second website we visit. The load more feature is used to load more or show more content available on the webpage to the visitor. Initially, half of the content is hidden, only some part of it i
4 min read
Java 8 | DoubleToIntFunction Interface in Java with Example
The DoubleToIntFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and gives an int-valued result. The lambda expression assigned to an object of DoubleToIntFunction type is used to define
1 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java Math asin() method with Example
The java.lang.Math.asin() returns the arc sine of an angle in between -pi/2 and pi/2. Arc sine is also called as an inverse of a sine. If the argument is NaN or its absolute value is greater than 1, then the result is NaN. If the argument is zero, then the result is a zero with the same sign as the argument. Syntax : public static double asin(doubl
1 min read
Arraylist lastIndexOf() in Java with example
The lastIndexOf() method of ArrayList in Java is used to get the index of the last occurrence of an element in an ArrayList object. Syntax : lastIndexOf(element) Parameter : The element whose last index is to be returned. Returns : It returns the last occurrence of the element passed in the parameter. It returns -1 if the element is not found. Prog
2 min read
ArrayList trimToSize() in Java with example
The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list's current size. This method is used to trim an ArrayList instance to the number of elements it contains. Syntax: trimToSize() Parameter: It does not accepts any parameter. Return Value: It does not returns any value. It trims the capacity of this
1 min read
ArrayList isEmpty() in Java with example
The isEmpty() method of ArrayList in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element. Syntax: list_name.isEmpty() Parameter: It does not accepts any parameter. Returns: It returns True if the list list_name has no elements else it returns f
2 min read
Practice Tags :