Implementing Spring Boot with Apache HTTP Client for External API Calls

In modern applications, communicating with external APIs is a common necessity. Whether you’re retrieving data from a third-party service or sending data to another application, having a robust HTTP client library is essential. Apache HTTP Client is a widely used library that provides a powerful and flexible way to make HTTP requests. In this post, we’ll explore how to integrate Apache HTTP Client with Spring Boot for making external API calls.

What is Apache HTTP Client?

Apache HTTP Client is a library that simplifies making HTTP requests. It supports HTTP/1.1 and HTTP/2, provides built-in support for cookies, connection pooling, and request retries, making it a versatile choice for various applications.

Setting Up Apache HTTP Client in Spring Boot

To start using Apache HTTP Client in your Spring Boot application, follow these steps:

1. Adding Dependencies

Add the following Maven dependency to your pom.xml file:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

Creating an HTTP Client Bean

To interact with external APIs effectively, it’s a good practice to create an HTTP client bean in your Spring Boot application. This allows for centralized configuration and easy reuse of the client:

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpClientConfig {

    @Bean
    public CloseableHttpClient httpClient() {
        return HttpClients.createDefault();
    }
}

Making HTTP Requests

Now, let’s create a service class that leverages the Apache HTTP Client to make GET and POST requests:

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.InputStreamReader;

@Service
public class ApiService {

    @Autowired
    private CloseableHttpClient httpClient;

    public String getData(String url) throws Exception {
        HttpGet request = new HttpGet(url);
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                StringBuilder result = new StringBuilder();
                try (BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()))) {
                    String line;
                    while ((line = rd.readLine()) != null) {
                        result.append(line);
                    }
                }
                return result.toString();
            }
        }
        return null;
    }

    public String postData(String url, String jsonData) throws Exception {
        HttpPost post = new HttpPost(url);
        post.setEntity(new StringEntity(jsonData));
        post.setHeader("Content-type", "application/json");
        try (CloseableHttpResponse response = httpClient.execute(post)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                StringBuilder result = new StringBuilder();
                try (BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()))) {
                    String line;
                    while ((line = rd.readLine()) != null) {
                        result.append(line);
                    }
                }
                return result.toString();
            }
        }
        return null;
    }
}

Creating REST Endpoints for the API Service

Let’s expose a REST endpoint to retrieve data from an external API:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @Autowired
    private ApiService apiService;

    @GetMapping("/fetch-data")
    public String fetchData(@RequestParam String url) throws Exception {
        return apiService.getData(url);
    }
}

Testing Your Implementation

Run your Spring Boot application and test the endpoint. Using Postman or cURL, you can fetch data from an external URL:

curl "http://localhost:8080/fetch-data?url=https://api.example.com/data"

Conclusion

Integrating Apache HTTP Client with Spring Boot provides a straightforward way to handle HTTP requests to external APIs, allowing your application to interact with a wide range of services seamlessly. Armed with this knowledge, you can extend functionality, integrate multiple services, and build robust applications.

For further insights, tips, and advanced patterns on using Spring Boot with external APIs, check out the extensive resources available at ITER Academy, which will help enhance your skills as a developer.

To learn more about ITER Academy, visit our website.

Scroll to Top