通用Http请求工具类(Hutool实现)

借助Hutool工具类自定义封装Http请求通用方法,如Get、Post、Put、Delete请求。

代码如下:

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * hutool通用http请求方法
 *
 * @author 逆行
 * @date 2024/04/12 15:48
 **/
public class HutoolHttpUtils
{

    private static final Logger log = LoggerFactory.getLogger(HutoolHttpUtils.class);

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url     发送请求的 URL
     * @param param   请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @param timeout 设置连接超时,单位:毫秒
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param, int timeout)
    {
        String responseBody = null;
        try
        {
            HttpResponse response = HttpRequest.get(url + "?" + param)
                    .addHeaders(getHeaders())
                    .setConnectionTimeout(timeout)
                    .execute();
            response.close();
            log.info("请求地址:{},\n请求参数:{},\n响应参数:{}", url, param, response.body());
            responseBody = response.body();
        } catch (IORuntimeException e)
        {
            log.error(e.getMessage(), e);
            throw new RuntimeException("请求连接超时");
        }
        return responseBody;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url     发送请求的 URL
     * @param param   请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @param timeout 设置连接超时,单位:毫秒
     * @return 所代表远程资源的响应结果
     */
    public static String sendPostWithUrlParam(String url, String param, int timeout)
    {
        String responseBody = null;
        try
        {
            HttpResponse response = HttpRequest.post(url + "?" + param)
                    .body(JSONUtil.toJsonStr(JSONUtil.createObj()))
                    .addHeaders(getHeaders())
                    .setConnectionTimeout(timeout)
                    .execute();
            response.close();
            log.info("请求地址:{},\n请求参数:{},\n响应参数:{}", url, param, response.body());
            responseBody = response.body();
        } catch (IORuntimeException e)
        {
            log.error(e.getMessage(), e);
            throw new RuntimeException("请求连接超时");
        }
        return responseBody;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url       发送请求的 URL
     * @param bodyParam 请求参数,请求参数应该是参数对象的JSON字符串形式。
     * @param timeout   设置连接超时,单位:毫秒
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, Object bodyParam, int timeout)
    {

        String responseBody = null;
        try
        {
            HttpResponse response = HttpRequest.post(url)
                    .body(JSONUtil.toJsonStr(bodyParam))
                    .addHeaders(getHeaders())
                    .setConnectionTimeout(timeout)
                    .execute();
            response.close();
            log.info("请求地址:{},\n请求参数:{},\n响应参数:{}", url, bodyParam.toString(), response.body());
            responseBody = response.body();
        } catch (IORuntimeException e)
        {
            log.error(e.getMessage(), e);
            throw new RuntimeException("请求连接超时");
        }
        return responseBody;
    }

    /**
     * 向指定 URL 发送PUT方法的请求
     *
     * @param url       发送请求的 URL
     * @param bodyParam 请求参数,请求参数应该是参数对象的JSON字符串形式。
     * @param timeout   设置连接超时,单位:毫秒
     * @return 所代表远程资源的响应结果
     */
    public static String sendPut(String url, Object bodyParam, int timeout)
    {
        String responseBody = null;
        try
        {
            HttpResponse response = HttpRequest.put(url)
                    .body(JSONUtil.toJsonStr(bodyParam))
                    .addHeaders(getHeaders())
                    .setConnectionTimeout(timeout)
                    .execute();
            response.close();
            log.info("请求地址:{},\n请求参数:{},\n响应参数:{}", url, bodyParam.toString(), response.body());
            responseBody = response.body();
        } catch (IORuntimeException e)
        {
            log.error(e.getMessage(), e);
            throw new RuntimeException("请求连接超时");
        }
        return responseBody;
    }

    /**
     * 向指定 URL 发送DELETE方法的请求
     *
     * @param url     发送请求的 URL
     * @param param   请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @param timeout 设置连接超时,单位:毫秒
     * @return 所代表远程资源的响应结果
     */
    public static String sendDelete(String url, String param, int timeout)
    {
        String responseBody = null;
        try
        {
            HttpResponse response = HttpRequest.get(url + "?" + param)
                    .addHeaders(getHeaders())
                    .setConnectionTimeout(timeout)
                    .execute();
            response.close();
            log.info("请求地址:{},\n请求参数:{},\n响应参数:{}", url, param, response.body());
            responseBody = response.body();
        } catch (IORuntimeException e)
        {
            log.error(e.getMessage(), e);
            throw new RuntimeException("请求连接超时");
        }
        return responseBody;
    }

    /**
     * 设置请求头
     */
    public static Map<String, String> getHeaders()
    {
        Map<String, String> headers = new HashMap<>();
        // add some header
        return headers;
    }
}