HTTP Client in Java 11

Reading Time: 3 minutes


An HttpClient can be used to send requests and retrieve their responses. It is a class that is introduced in java 9 in the incubator module. In java 11 version it is moved to the java.net.http package.

The introduction of this class in java 11 helps us to send the HTTP request without using any third-party API like an apache httpClient or httpasyncclient. Httpasyncclient API was complex for sending the async calls. However, with this class, we can send the synchronous and asynchronous requests easily.

We can build the Http Client through the builder also. It is an immutable object can be used to send multiple request.

A bodyHandlde must be send for each httpRequest. It determine how to handle the response that we get for http Request.

How to make a client object?

We can make HttpClient by using the newHttpClient method.

HttpClient client = HttpClient.newHttpClient();

HttpClient can also be made through builder.  We have to also provide some properties on how the httpCLient can behave.

HttpClient client = HttpClient.newBuilder()
        .version(Version.HTTP_1_1)
        .connectTimeout(Duration.ofSeconds(20))
        .build();

In the second example we can see that we have provided that what version of http Client we have to use. We can also provide authentication to client as well.

We can send the synchronous request as well as asynchronous request.

Following are methods to send request.

  • send(HttpRequest, BodyHandler): It is a blocking call. Blocks until the request has been sent and the response has been received.
  • sendAsync(HttpRequest, BodyHandler): It is a non-blocking call. Sends the request and receives the response asynchronously. It will return the CompletableFuture immediately . The CompletableFuture completes when the response becomes available.

How to send the request using the above methods.

    HttpRequest request = HttpRequest.newBuilder(URI.create("http://httpbin.org/post"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString("{\n"
                    + "   \"json\":null,\n"
                    + "   \"origin\":\"112.196.145.8\",\n"
                    + "   \"url\":\"http://httpbin.org/patch\"\n"
                    + "}"))
        .build();

    client.send(request, HttpResponse.BodyHandlers.ofString());

It is an example of the synchronous call we have used the send method in the last line. It takes two parameters first one is request and second is BodyHandler that is used to send a response. You can see that we have made an request using the HttpRequest call in which we specified the header, POST specify that it is a POST request and inside its parameter we specify the body for the post request using the BodyPublishers, it is used in the POST, PUT and method for providing the request body. Once all required parameters have been set in the builder, build will return the HttpRequest.

    HttpRequest request = HttpRequest.newBuilder(URI.create("http://httpbin.org/post"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString("{\n"
                    + "   \"json\":null,\n"
                    + "   \"origin\":\"112.196.145.8\",\n"
                    + "   \"url\":\"http://httpbin.org/patch\"\n"
                    + "}"))
        .build();

    CompletableFuture<String> stringCompletableFuture = client
                .sendAsync(request, HttpResponse.BodyHandlers.ofString());

It is an example of an async call we can see CompletableFuture of string has been sent. The sendAsync will return the CompletableFuture<HttpResponse<String>>. We can handle it like any other completable future call. Rest is the same as synchronous call.

How to send the Concurrent Request?

We can send the concurrent Requests with this class as well.

  private static List<CompletableFuture<String>> concurrentCalls(final List<URI> urlList) {

        return urlList.stream()
                .map(url -> client.sendAsync(
                        HttpRequest.newBuilder(url)
                                .GET().build(),
                        HttpResponse.BodyHandlers.ofString())
                        .thenApply(response -> response.body()))
                .collect(Collectors.toList());
    }

In the above example we see that we provided the List of URI in the method. We have applied the map operation and send the async get http request. After that we have collected its result as a list. List of CompletableFuture<String> is formed.

For more detailed examples like how to send different requests with Http methods. How to provide a request body if you have an object to represent the request body. You can refer to my gitHub repository.

That’s all for the small introduction for the httpClient if you have any queries or want to know more about it you can add the comments below. I am happy to answer them. 🙂

References

Java Documentation
Java blog

Knoldus-blog-footer-image

+ posts

Priyanka Thakur is a Software Consultant having 6 months of experience currently working at Knoldus Software LLP. She has done MCA at BVICAM, GGSIPU. She has a graduation degree in BCA from JIMS, GGSIPU.
She is familiar with programming language' s such as C, Java, and Scala. She also has interest in Angular and Docker and currently working on Logam.
She is dedicated, focused and hardworking person. Her interests are in to face new programming challenges because she believes these challenges produce opportunity. She is keen to learn new technologies. In her leisure time, she prefers reading about mythology, watching movies.

Written by 

Priyanka Thakur is a Software Consultant having 6 months of experience currently working at Knoldus Software LLP. She has done MCA at BVICAM, GGSIPU. She has a graduation degree in BCA from JIMS, GGSIPU. She is familiar with programming language' s such as C, Java, and Scala. She also has interest in Angular and Docker and currently working on Logam. She is dedicated, focused and hardworking person. Her interests are in to face new programming challenges because she believes these challenges produce opportunity. She is keen to learn new technologies. In her leisure time, she prefers reading about mythology, watching movies.