Making GET Requests and Handling Responses in Java Using HttpClient and Gson

Making GET Requests and Handling Responses

Welcome to the second lesson in our journey of interacting with APIs using Java. In the previous lesson, we laid a strong foundation by understanding RESTful APIs and how HTTP requests facilitate interactions with them. We used curl to manually craft and send a GET request to an endpoint. Now, we are transitioning to automating this process using Java. This lesson introduces the HttpClient from the java.net.http package, which allows us to send HTTP requests effortlessly in our Java applications. Alongside, we'll use the Gson library for parsing JSON responses, making these tools invaluable in the realm of web development and API integration.

Setting Up the Environment

To make HTTP requests in Java, we leverage the HttpClient, which is part of the core java.net.http package starting from Java 11. For JSON parsing, we use the Gson library. To integrate these tools into your Java project, ensure your environment is set up properly.

  1. Java Development Kit (JDK):

    • Ensure you have JDK version 11 or higher installed on your machine.
  2. Gson Library:

    • Include Gson in your project by adding it to your pom.xml if you are using Maven:
      <dependency>
          <groupId>com.google.code.gson</groupId>
          <artifactId>gson</artifactId>
          <version>2.12.1</version>
      </dependency>
    • Or if you are using gradle:
    implementation 'com.google.code.gson:gson:2.12.1'

But you don't have to worry about that here, we've set it all up for you!

Defining the Base URL

When interacting with an API, it's helpful to define a base URL for the service you're communicating with. This design choice makes your code more modular and easy to maintain, allowing you to change the root of your API URL in one place without modifying each request.

// Base URL for the API
String baseUrl = "http://localhost:8000";

By setting this base URL, we can easily concatenate endpoints for different services within the API, making our code cleaner and more adaptable.

Performing a Basic GET Request

Let's dive into the process of fetching data from an API using Java's HttpClient. Our goal is to retrieve a list of to-do items from the /todos endpoint using the GET method.

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class ApiInteraction {

    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(baseUrl + "/todos"))
                .GET() // Can be left out as GET is the default request type
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Raw Response:");
        System.out.println(response.body());
    }
}

By using the HttpClient, we send a GET request to the constructed full URL. The response from the server, stored in the variable response, is then printed, providing us with the raw response body as a string.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal