Perform HTTP Calls using Java 11 HttpClient - Part 1

Making GET call using Java 11 HTTP Client - Java Dev ビット

Perform HTTP Calls using Java 11 HttpClient - Part 1

While creating backend services, we can encounter certain scenarios where we need data from external / 3rd Party services. These external services have different protocols through which one can communicate with them, HTTP(HyperText Transfer Protocol) is the most common protocol.

There are many external Java libraries that provide utilities for making these HTTP calls.

In this article, we will look at how we can make HTTP calls (in particular GET Call) HttpClient provided in Java version 11. Let's start.

Step 1 : Initializing the HttpClient

import java.net.http.HttpClient;
final HttpClient client= HttpClient.newHttpClient();

We can use the static method newHttpClient provided by the HttpClient class. Another way of initializing HttpClient is by using newBuilder method like:

final HttpClient client = HttpClient.newBuilder().build();

Step 2: Creating a Request Object

import java.net.http.HttpRequest;
final String url = "https://jsonplaceholder.typicode.com/posts";
final HttpRequest request = 
                HttpRequest
                .newBuilder(URI.create(url))
                .GET()
                .build();

The above code snippet builds the HTTP request. In this, we are providing the external service's API URL and adding which GET HTTP verb for creating a GET request.

jsonplaceholder.typicode.com- Check out the site, it provides mock APIs. These mock APIs save a lot of time, during web development.

Step 3: Executing the Request

import java.net.http.HttpRequest;
final HttpResponse<String> response = 
        client.send(request, BodyHandlers.ofString());

Now, let's execute the GET request by using send provided by the client object created earlier. The response object exposes many functions to get the details of the response from the external service.

response.statusCode(); // For extracting HTTP status code.
response.body(); // For extracting the content of HTTP Response.

We have successfully made a GET call in 3 simple steps. That's it for this Dev ビット.

Bonus

response.body(); // For extracting the content of HTTP Response.

The above function returns a value with the String datatype, so if the content that is coming from the API is of type JSON(Javascript Object Notation) then you can use something called Object Serializers/ Deserializers to convert JSON string to Java object.

Popular Object Serializers/ Deserializers Libraries.

Previous Articles

Feel free to reach out on my Twitter. Check out my other projects on my Github.

Blog_Footer_small_badge.png