SoFunction
Updated on 2025-05-12

Several commonly used HTTP request tool classes in Java are explained in detail

1. Use hutool

Introduce dependencies

        <dependency>
            <groupId></groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.8</version>
        </dependency>

Tools

package ;

import ;
import ;
import ;

import ;

public class HttpUtilTools {

    /**
      * Initiate HTTP requests (supports GET and POST)
      *
      * @param serverPrefix server prefix
      * @param urlSuffix URL path suffix
      * @param method HTTP request method
      * @param headers Request header
      * @param params request parameters (JSON body when POST, query parameters when GET)
      * @return Request result string
      */
    public static String sendRequest(String serverPrefix, String urlSuffix, String method, Map&lt;String, String&gt; headers, Map&lt;String, Object&gt; params) {
        HttpRequest request;
        if ("GET".equalsIgnoreCase(method)) {
            request = (serverPrefix + urlSuffix);
            if (params != null) {
                (request::form);
            }
        } else if ("POST".equalsIgnoreCase(method)) {
            String jsonStr = (params);
            request = (serverPrefix + urlSuffix)
                    .body(jsonStr);
            ("Content-Type", "application/json"); // The default setting of Content-Type is JSON        } else {
            throw new IllegalArgumentException("Unsupported HTTP method: " + method);
        }

        // Set request header        if (headers != null) {
            (request::header);
        }

        // Execute the request and get the response        HttpResponse response = ();
        return ();
    }

    // Convenient GET request method    public static String sendGetRequest(String serverPrefix, String urlSuffix, Map&lt;String, String&gt; headers, Map&lt;String, Object&gt; params) {
        return sendRequest(serverPrefix, urlSuffix, "GET", headers, params);
    }

    // Convenient POST request method    public static String sendPostRequest(String serverPrefix, String urlSuffix, Map&lt;String, String&gt; headers, Map&lt;String, Object&gt; params) {
        return sendRequest(serverPrefix, urlSuffix, "POST", headers, params);
    }
}

Called:

import ;
import ;

public class Main {
    public static void main(String[] args) {
        String serverPrefix = "";
        
        // Prepare the parameters for the GET request        Map&lt;String, Object&gt; getParams = new HashMap&lt;&gt;();
        ("page", 1);
        ("pageSize", 1000);
        
        // Prepare the header of the GET request        Map&lt;String, String&gt; getHeaders = new HashMap&lt;&gt;();
        ("x-auth-token", "your-auth-token");
        ("Custom-Header", "CustomValue");
        
        // Initiate a GET request        String getResponse = (serverPrefix, "/api/v1/projects/page", getHeaders, getParams);
        ("GET Response: " + getResponse);
        
        // Prepare the parameters of the POST request        Map&lt;String, Object&gt; postParams = new HashMap&lt;&gt;();
        ("page", 1);
        ("pageSize", 1000);
        ("parentId", "your-parent-id");
        
        // Prepare the header of the POST request        Map&lt;String, String&gt; postHeaders = new HashMap&lt;&gt;();
        ("x-auth-token", "your-auth-token");
        ("Content-Type", "application/json"); // Although the tool class will be set internally, it can be customized here.        
        // Initiate a POST request        String postResponse = (serverPrefix, "/api/v1/media/projects/your-project-id/files", postHeaders, postParams);
        ("POST Response: " + postResponse);
    }
}

2. Use okhttp

Introduce dependencies

        <dependency>
            <groupId>.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.14.9</version>
        </dependency>

Tools

package ;

import ;
import okhttp3.*;

import ;
import ;
import ;

public class HttpClientUtils {

    private static final OkHttpClient httpClient = new ()
            .connectTimeout(60, ) // Connection timeout 60 seconds            .readTimeout(60, )    // Read timeout 60 seconds            .writeTimeout(60, )   // Write timeout 60 seconds            .build();

    public static final MediaType MEDIA_TYPE_JSON = ("application/json; charset=utf-8");

    public static JSONObject get(String url) {
        Request request = new ().url(url).get().build();
        return execute(request);
    }

    public static JSONObject get(String url, Map&lt;String, String&gt; headers) {
         requestBuilder = new ().url(url).get();
        // Add request header        if (headers != null) {
            for (&lt;String, String&gt; entry : ()) {
                ((), ());
            }
        }
        Request request = ();
        return execute(request);
    }

    public static JSONObject post(String url, JSONObject content) {
        RequestBody body = (MEDIA_TYPE_JSON, ());
        Request request = new ().url(url).post(body).build();
        return execute(request);
    }

    public static JSONObject post(String url, JSONObject content, Map&lt;String, String&gt; headers) {
        RequestBody body = (MEDIA_TYPE_JSON, ());
         requestBuilder = new ().url(url).post(body);
        // Add request header        if (headers != null) {
            for (&lt;String, String&gt; entry : ()) {
                ((), ());
            }
        }
        Request request = ();
        return execute(request);
    }

    private static JSONObject execute(Request request) {
        try (Response response = (request).execute()) {
            if (!()) {
                throw new IOException("Unexpected code " + response);
            }
            String str = ().string();
            return (str);
        } catch (IOException e) {
            ();
            return new JSONObject();
        }
    }
}

3. Use the RestTemplate that comes with spring

Tools

package ;

import ;
import .;
import .*;
import ;
import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;


public class HttpUtil {
    private static final RestTemplate REST_TEMPLATE = new RestTemplate();

    static {
        // Set the timeout to 60S        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        (60000);
        (60000);
        REST_TEMPLATE.setRequestFactory(requestFactory);
        // Add a request interceptor to print request information        REST_TEMPLATE.getInterceptors().add(new ClientHttpRequestInterceptor() {
            @Override
            public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException, IOException {
                ("sendPost:   url = " + () + ",headers=" + ());
                return (request, body);
            }
        });
    }
    /**
      * Send POST request Enter parameter: request body, request body format type
      */
    public static &lt;T&gt; T sendPost(String url, Object bodyParams, Class&lt;T&gt; clazz) {
        Map&lt;String, Object&gt; headerParam = new HashMap&lt;&gt;();
        ("Content-Type", "application/json");
        ("Connection", "close");
        HttpEntity&lt;String&gt; httpEntity = formatHeaders(bodyParams, headerParam);
        ResponseEntity&lt;T&gt; responseEntity = REST_TEMPLATE.postForEntity(url, httpEntity, clazz);
        return ();
    }

    /**
      * Send POST request (with request header)
      */
    public static &lt;T&gt; T sendPostWithHeader(String url, Object bodyParams, Map&lt;String, Object&gt; headerParams, Class&lt;T&gt; clazz) {
        HttpEntity&lt;String&gt; httpEntity = formatHeaders(bodyParams, headerParams);
        ResponseEntity&lt;T&gt; responseEntity = REST_TEMPLATE.postForEntity(url, httpEntity, clazz);
        return ();
    }

    /**
      * Send GET request without request header
      * @return
      */
    public static &lt;T&gt; T sendGet(String url, Map&lt;String, Object&gt; params, Class&lt;T&gt; clazz) throws MalformedURLException {
        String realUrl = formatGetParams(url, params);
        ResponseEntity&lt;T&gt; responseEntity = REST_TEMPLATE.getForEntity(realUrl, clazz);
        return ();
    }

    /**
      * Send GET request with request header
      */
    public static &lt;T&gt; T sendGetWithHeader(String url, Map&lt;String, Object&gt; params, Map&lt;String, Object&gt; headerParams, Class&lt;T&gt; clazz) {
        String realUrl = formatGetParams(url, params);
        HttpEntity&lt;String&gt; httpEntity = formatHeaders(null, headerParams);
        ResponseEntity&lt;T&gt; responseEntity = REST_TEMPLATE.exchange(realUrl, , httpEntity, clazz);
        return ();
    }

    /**
      * Format Get request url
      *
      * @param params
      * @return
      */
    public static String formatGetParams(String url, Map&lt;String, Object&gt; params) {
        ("formatGetParams=" + params);
        StringBuilder sb = new StringBuilder();
        (url).append("?");
        try {
            Set&lt;String&gt; keySet = ();
            Iterator&lt;String&gt; iterator = ();
            while (()) {
                String key = ();
                String value = ((key));
                if ("params".equals(key)) {
                    value = (value, StandardCharsets.UTF_8.toString());
                }
                (key).append("=").append(value).append("&amp;");

            }
            return (0, () - 1);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    /**
      * Format Get request header parameters
      *
      * @param body body parameter
      * @param headerParams request header parameters
      * @return httpEntity
      */
    private static HttpEntity&lt;String&gt; formatHeaders(Object body, Map&lt;String, Object&gt; headerParams) {
        HttpHeaders httpHeaders = new HttpHeaders();
        if (headerParams != null &amp;&amp; () &gt; 0) {
            for (&lt;String, Object&gt; entry : ()) {
                ((), ().toString());
            }
        }
        //Judge whether the body parameter is empty        if ((body)) {
            return new HttpEntity&lt;&gt;(httpHeaders);
        } else {
            return new HttpEntity&lt;&gt;((body), httpHeaders);
        }
    }
}

Summarize:

Performance comparisonOkHttp:

Highest performance: OkHttp is an HTTP client specially designed for high performance, supporting optimizations such as connection pooling, request interceptor, GZIP compression, etc.
Suitable for high concurrency scenarios: If your application needs to handle a large number of HTTP requests, OkHttp is the best choice.
Hutool:

Medium performance: Hutool's HTTP tool is implemented based on JDK's HttpURLConnection, and its performance is not as good as OkHttp, but it is sufficient for most scenarios.
Suitable for small projects: If your project is not very performance-oriented and requires rapid development, Hutool is a good choice.
RestTemplate:

Medium performance: RestTemplate is implemented based on JDK's HttpURLConnection or Apache's HttpClient, and its performance is similar to Hutool.
Suitable for Spring projects: If your project already uses the Spring framework, RestTemplate can integrate well with the Spring ecosystem.

Recommended usage scenariosHutool:

Suitable for small projects or tool requirements.
If you need to implement HTTP requests quickly and don't want to introduce complex dependencies, Hutool is a good choice.
OkHttp:

Suitable for high-performance requirements or complex HTTP request scenarios.
If you need to handle a large number of concurrent requests, or need to customize request interceptors, connection pools, etc., OkHttp is the best choice.
RestTemplate:

Suitable for Spring projects.
If your project already uses the Spring framework and needs to integrate with the Spring ecosystem (such as Spring Boot, Spring Cloud), RestTemplate is a good choice.

This is the end of this article about several commonly used HTTP request tool classes in Java. For more related contents of HTTP request tool classes, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!