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("调用接口出现异常!");
    }


}

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

相关推荐
骆晨学长10 分钟前
基于springboot的智慧社区微信小程序
java·数据库·spring boot·后端·微信小程序·小程序
LyaJpunov12 分钟前
C++中move和forword的区别
开发语言·c++
AskHarries15 分钟前
利用反射实现动态代理
java·后端·reflect
@月落15 分钟前
alibaba获得店铺的所有商品 API接口
java·大数据·数据库·人工智能·学习
程序猿练习生16 分钟前
C++速通LeetCode中等第9题-合并区间
开发语言·c++·leetcode
liuyang-neu21 分钟前
力扣 42.接雨水
java·算法·leetcode
z千鑫24 分钟前
【人工智能】如何利用AI轻松将java,c++等代码转换为Python语言?程序员必读
java·c++·人工智能·gpt·agent·ai编程·ai工具
一名路过的小码农26 分钟前
C/C++动态库函数导出 windows
c语言·开发语言·c++
m0_6312704029 分钟前
标准c语言(一)
c语言·开发语言·算法
万河归海42829 分钟前
C语言——二分法搜索数组中特定元素并返回下标
c语言·开发语言·数据结构·经验分享·笔记·算法·visualstudio