Java 发送 Http 请求工具类(HttpClient)

java 复制代码
import com.gientech.exception.BusinessException;
import com.gientech.util.LoggerUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

/**
 *
 * HttpClient
 * @author xiarg
 * @date 2023/11/1 17:18
 */
public class TdspHttpClient {

    private static final Logger logger = LoggerFactory.getLogger(TdspHttpClient.class);

    @Autowired
    private static CloseableHttpClient httpClient;

    static {
        httpClient = HttpClientBuilder.create().build();
    }

    /**
     *
     * http的get请求
     * @param url 请求路径
     * @return null
     * @author xiarg
     * @date 2023/11/2 13:35
     */
    public static String sendGetRequest(String url,String responseCharset) throws Exception{
        LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>接口请求start<<<<<===== {0}", url);
        HttpEntity entity = null;
        String result = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);
            return handleResponse( response, responseCharset);
        } catch (IOException e) {
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>发送请求出现异常<<<<<===== {0}",
                    e.getMessage());
            e.printStackTrace();
        } catch (ParseException e) {
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>发送请求出现异常<<<<<===== {0}",
                    e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (IOException e) {
                LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>清理缓存出现异常<<<<<===== {0}",
                        e.getMessage());
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     *
     * http的post秦秋
     * @param url
     * @param requestBody
     * @param contentType 媒体类型
     * @param entryCharset 请求报文编码
     * @param responseCharset 响应报文编码
     * @return null
     * @author xiarg
     * @date 2023/11/2 13:36
     */
    public static String sendPostRequest(String url, String requestBody, String contentType ,String entryCharset,
                                         String responseCharset) throws Exception{
        LoggerUtil.info(logger, "[HttpClientUtils.sendPostRequest]=====>>>>>接口请求start<<<<<===== {0}", url);
        HttpEntity entity = null;
        String result = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            ContentType entryContentType = ContentType.create(contentType, Charset.forName(entryCharset));
            httpPost.setEntity(new StringEntity(requestBody, entryContentType));
            HttpResponse response = httpClient.execute(httpPost);
            return handleResponse(response,responseCharset);
        } catch (UnsupportedCharsetException e) {
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>发送请求出现异常<<<<<===== {0}",
                    e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>发送请求出现异常<<<<<===== {0}",
                    e.getMessage());
            e.printStackTrace();
        } catch (ParseException e) {
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>发送请求出现异常<<<<<===== {0}",
                    e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (IOException e) {
                LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>清理缓存出现异常<<<<<===== {0}",
                        e.getMessage());
                e.printStackTrace();
            }
        }
        return result;
    }

    private static String handleResponse(HttpResponse response,String responseCharset) throws IOException,BusinessException{
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode >= 200 && statusCode < 300) {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity,Charset.forName(responseCharset));
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>接口请求返回结果<<<<<===== {0}",
                    result);
            return result;
        }
        throw new BusinessException("调用接口出现异常!");
    }


}

此工具类可以直接复制使用。

相关推荐
留不住丨晚霞17 分钟前
说说SpringBoot常用的注解?
java·开发语言
华科云商xiao徐23 分钟前
Java多线程爬虫动态线程管理实现
java·爬虫·数据挖掘
hardStudy_h27 分钟前
C++——内联函数与Lambda表达式
开发语言·jvm·c++
柒七爱吃麻辣烫32 分钟前
八股文系列-----SpringBoot自动配置的流程
java·spring boot·rpc
M1A137 分钟前
Java 面试系列第一弹:基础问题大盘点
java·后端·mysql
发仔12337 分钟前
Dubbo介绍及示例用法
java·dubbo
goxingman1 小时前
关于使用idea打包的时候报错,Maven提示乱码java: �Ҳ�������
java·maven·intellij-idea
艾莉丝努力练剑1 小时前
【C语言】学习过程教训与经验杂谈:思想准备、知识回顾(三)
c语言·开发语言·数据结构·学习·算法
邓不利东2 小时前
Spring中过滤器和拦截器的区别及具体实现
java·后端·spring
witton2 小时前
Go语言网络游戏服务器模块化编程
服务器·开发语言·游戏·golang·origin·模块化·耦合