Seven Methods for Implementing HTTP Calls in Spring Boot

Seven Methods for Implementing HTTP Calls in Spring Boot
Hello everyone, I am Xia Yi.
Today I will share about HTTP calling methods.

Most projects are currently using the Spring Boot framework, and HTTP calls are an inevitable part of daily development.

Whether calling third-party APIs or implementing communication between microservices, HTTP requests play a crucial role.

This article will introduce seven efficient and commonly used methods for making HTTP calls.

1. HttpClient

<span>HttpClient</span> is a Java client library provided by the Apache Foundation for sending HTTP requests.

Although it is powerful, its API design is relatively complex and its package size is large, which may seem overly cumbersome in some lightweight application scenarios.

However, when highly customized HTTP requests are needed, <span>HttpClient</span> is still a good choice.

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpClientUtil {

    public static String get(String url) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(12000)
                .setConnectionRequestTimeout(12000)
                .setSocketTimeout(12000)
                .build();

        HttpGet request = new HttpGet(url);
        request.setConfig(config);

        try (CloseableHttpResponse response = httpClient.execute(request)) {
            // Handle response
            return "Response received";
        } catch (Exception e) {
            throw new RuntimeException("HTTP call failed", e);
        }
    }
}

2. OkHttp

<span>OkHttp</span> is a modern HTTP client that provides a concise and efficient API.

Compared to <span>HttpClient</span>, <span>OkHttp</span> is more lightweight and easier to use.

<span>OkHttp</span> supports synchronous and asynchronous requests and provides advanced features such as connection pooling, GZIP compression, and caching.

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpUtil {

    private static final OkHttpClient CLIENT = new OkHttpClient();

    public static String get(String url) throws Exception {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = CLIENT.newCall(request).execute()) {
            // Handle response
            return response.body().string();
        }
    }
}

3. OkHttpUtil (Wrapper)

To simplify the use of <span>OkHttp</span>, we can wrap it to provide a more user-friendly API interface.

<span>OkHttpUtil</span> wrapper is such a utility class that makes HTTP requests exceptionally simple.

// Assume we already have a wrapped OkHttpUtil class
public class OkHttpUtilWrapper {

    public static String get(String url, Map<String, Object> queryParams) throws IOException {
        // Assume OkHttpUtil provides such a get method
        return OkHttpUtil.get(url, queryParams);
    }
}

4. Jodd HTTP

<span>Jodd HTTP</span> is another lightweight HTTP client library that provides a simple API and efficient performance.

<span>Jodd HTTP</span> supports various HTTP methods, request headers, query parameters, and form data, making it very suitable for quickly building HTTP requests.

import jodd.http.HttpRequest;
import jodd.http.HttpResponse;

public class JoddHttpUtil {

    public static String get(String url, Map<String, Object> queryParams) throws IOException {
        HttpRequest request = HttpRequest.get(url).query(queryParams);
        HttpResponse response = request.send();
        return response.bodyText();
    }
}

5. Hutool HTTP

<span>Hutool</span> is a Java utility library that contains a rich set of HTTP utility classes.

<span>Hutool HTTP</span> provides simple yet powerful HTTP request capabilities, supporting various HTTP methods such as GET, POST, PUT, DELETE, and includes built-in connection pooling and retry mechanisms.

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

public class HutoolHttpUtil {

    public static String get(String url, Map<String, Object> queryParams) throws IOException {
        HttpRequest request = HttpUtil.createGet(url).form(queryParams);
        HttpResponse response = request.execute();
        return response.body();
    }
}

6. RestTemplate

<span>RestTemplate</span> is a synchronous HTTP client tool provided by the Spring framework that simplifies communication with HTTP services and unifies exception handling.

<span>RestTemplate</span> supports RESTful style URL templates and request parameter binding, making it very suitable for interacting with RESTful services.

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;

@Component
public class RestTemplateUtil {

    private final RestTemplate restTemplate;

    public RestTemplateUtil(RestTemplateBuilder builder) {
        this.restTemplate = builder.build();
    }

    public String get(String url, Map<String, Object> queryParams) {
        String uri = buildUri(url, queryParams);
        ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
        return response.getBody();
    }

    private String buildUri(String url, Map<String, Object> queryParams) {
        // Logic to build URI
        return url;
    }
}

7. Forest

<span>Forest</span> is a declarative HTTP client framework that allows developers to define HTTP requests in an interface manner.

<span>Forest</span> provides a concise API and powerful features such as request retries, timeout settings, request headers, etc., making it very suitable for building complex HTTP request scenarios.

# application.yml
forest:
  max-connections: 1000
  connect-timeout: 3000
  read-timeout: 3000
import com.dtflys.forest.annotation.Get;
import com.dtflys.forest.annotation.Post;
import com.dtflys.forest.annotation.Query;
import com.dtflys.forest.annotation.Header;
import com.dtflys.forest.annotation.JSONBody;
import com.dtflys.forest.springboot.annotation.ForestScan;
import org.springframework.stereotype.Component;

@ForestScan(basePackages = "com.example.client")
@Component
public interface TestClient {

    @Get("http://localhost:20001/test/queryById")
    String queryById(@Header Map<String, Object> headerMap, @Query Map<String, Object> params);

    @Post("http://localhost:20001/test/add")
    String add(@Header Map<String, Object> headerMap, @JSONBody UserVo userVo);
}

In Spring Boot projects, by configuring <span>Forest</span> and defining interfaces, developers can easily initiate HTTP requests without worrying about the underlying details.

Conclusion

This article has shared seven efficient methods for implementing HTTP calls in Spring Boot projects, including <span>HttpClient</span>, <span>OkHttp</span>, <span>OkHttpUtil</span> wrapper, <span>Jodd HTTP</span>, <span>Hutool HTTP</span>, <span>RestTemplate</span>, and <span>Forest</span>.

Each method has its unique advantages and applicable scenarios, and everyone can choose the appropriate method for HTTP calls based on actual needs.

That’s all for today, see you in the next article.

Leave a Comment