HTTP2 client in java with coding example

Dsforgood
2 min readFeb 2, 2022

--

In this article we will take a look on java 11 standardization of HTTP2 client. We will then take a look at a program which will send and receive HTTP request and response respectively. After this article you will be able to efficiently send HTTP request from your java code. Before reading this article you should have a good understanding on terminologies such as HTTP, request, response.

HTTP requests before java11

Before java 11 we use URL and URLConnection classes for making HTTP connection in our java code. But there are some problems in it,

· It supports HTTP/1.1 protocol only.

· It works on blocking mode. It is not asynchronous.

· Maintenance is high.

The new HTTP2 client and its features

The new API was incubated in java 9 and 10 and standardized in java 11. Now it is part of java SE. Now let us look at some of the classes and interfaces in this API.

· The HttpClient class, java.net.http.HttpClient

· The HttpRequest class, java.net.http.HttpRequest

· The HttpResponse<T> interface, java.net.http.HttpResponse

Now let us discuss some of the features of this API,

· There are performance improvements with new changes such as stream multiplexing, header compression and push promises.

· The API is fully asynchronous which means we can send and receive multiple requests simultaneously.

· We no longer need third party library for sending HTTP2 requests.

· The APIs provide native support for HTTP 1.1/2 WebSocket.

Program to demonstrate HTTP request and response

Enough of theory now let us get to coding. In this example I am using java 17 for development. First we need to add a module dependency which is as shown below.

Now we will write code for HTTP connection. In this example we will connect to google.com and get our response back as a String. Below is the complete code for it.

In the above class Example2 in the main method we will create a HttpClient object by the static method newHttpClient() of the same class. Then we will start our try block in which we will create HttpRequest object. While building this object we will pass URI of the website and use GET as our HTTP request method. The final step is to send this request and get our response back. We will use send method of HttpClient class and we will pass request object and response type as HttpResponse.BodyHandlers.ofString(). Finally we will print the response body. We will handle the exceptions in the catch block.

Thank you for reading this article. If you are interested in learning java 17 I have a complete course for you please click here -> https://www.udemy.com/course/java-17-complete-course/?referralCode=C1A5CE9D4178AB159247

--

--

Dsforgood

We are a bunch of data science enthusiasts simplifying concepts and ideas in technology for common readers. We believe in using data science for good!