Introduction to HTTP Client in Java 11

woman coding on computer
Reading Time: 3 minutes

If you want to send a HTTP request and process the response from a java program you may need an API called HttpClient.

http-logo

What is HTTP?

The Hypertext Transfer Protocol (HTTP) is used to transmit data on the World Wide Web. It allows the client to send a request to a server and get the response back from the server. HTTP is used to request and transmit a wide variety of data, including HTML documents, images, videos, and other media.

HttpClient

The HTTPClient library was introduced in Java 11, before that developer has to use some third-party libraries such as Apache Http Client, OkHttp, or the legacy class HttpUrlConnection. HTTPClient replaces the HttpUrlConnection class present in the JDK since the early version of java. HttpClient is immutable, and can be used to send multiple requests. It provides a lot of useful and self-describing methods we can use to handle our request and response. It supports both HTTP/1.1 and HTTP/2, by default the client sends requests using HTTP/2, if the request sent to the servers does not support HTTP/2 then it will automatically be downgraded to HTTP/1.1.

httpclient-logo

Challenges with the HttpUrlConnection

The HttpUrlConnection API had some problems.

  • It works with blocking mode only for example you only can send a request in a synchronous way.
  • Very hard to maintain.
  • It supports only HTTP/1.1 protocol but not HTTP/2

Steps to use

  • First, we need to create a HttpClient instance.
  • Then create an HttpRequest instance using HttpRequest.newBuilder() instance.
  • After that, we will send a request by using send() method of HttpClient.
  • And get the response as a HttpResponse class object, the response will be returned as HttpResponse type.

In this example, we will use Java 11 HttpClient APIs to send HTTP GET/POST requests, and some frequently used examples.

Create HttpClient object from its builder-

HttpClient httpClient = HttpClient.newBuilder().build();

HttpRequest

The HttpRequest creates from its builder. The request builder can be used to set request URI, and request method such as GET, POST, PUT, request body, timeout and request headers. You can create new instances by using HttpRequest.Builder.

In the creation of a request, you can choose any of the versions like HTTP_2 or HTTP_1, we will go for HTTP_2 in this example. We send a GET request to a URL that will return a joke as a response. We specify the URI and request method. (If we don’t specify a request method, it will use the default GET method.) The HttpRequest is immutable but you can send it multiple times.

final String url = "https://official-joke-api.appspot.com/random_joke";
HttpRequest httpRequest = HttpRequest.newBuilder(URI.create(url))
                .version(HttpClient.Version.HTTP_2)
                .GET()
                .build();

After creating a httpRequest object now its time to send a request and get a response. The HttpResponse will hold the returned object as a response. The HttpResponse class has some most useful methods that we can use such as statusCode, headers, and body.

HttpResponse response = httpClient.send(httpRequest,BodyHandlers.ofString());

Now the response is ready you can get the body and headers of the response by using following methods. for example.

System.out.println("Status code: " + response.statusCode());
System.out.println("Headers: " + response.headers()
                                .allValues("content type"));
System.out.println("Body: " + response.body());

Let’s look at an example of sending a GET request asynchronously. We will use the sendAsync() method which returns a CompletableFeature to process a request asynchronously.

public void printUserInfo(){
     String url = "https://randomuser.me/api/";
     HttpRequest httpRequest = HttpRequest.newBuilder(URI.create(url)).build();
httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString())
                .thenApply(HttpResponse::body)
                .thenAccept(System.out::println)
                .join();
}

Synchronous or Asynchronous

We can send a request to a server either synchronously or asynchronously. The synchronous API blocks until the HttpResponse is available. But in the case of the asynchronous way, it returns immediately with a CompletableFuture that completes with the HttpResponse when it becomes available. it does not wait for the response, which is called non-blocking.

Features

  • The HttpClient supports both HTTP/1.1 and HTTP/2 and WebSocket.
  • It supports both synchronous and asynchronous programming models.
  • It has the ability to handle the request and response bodies as reactive streams.
  • Support for cookies

Written by 

Aasif Ali is a Software Consultant at Knoldus Inc. He has done Post Graduation from Quantum University Roorkee. He has the knowledge of various programming languages. He is passionate about Java development and curious to learn Java Technologies. He is always impatient and enthusiastic to learn new things. He is a quick learner, problem solver and always enjoy to help others. His hobbies are watching Sci-fi movies , Playing badminton and listening to songs.