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


}

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

相关推荐
2401_857439691 小时前
SSM 架构下 Vue 电脑测评系统:为电脑性能评估赋能
开发语言·php
SoraLuna2 小时前
「Mac畅玩鸿蒙与硬件47」UI互动应用篇24 - 虚拟音乐控制台
开发语言·macos·ui·华为·harmonyos
xlsw_2 小时前
java全栈day20--Web后端实战(Mybatis基础2)
java·开发语言·mybatis
神仙别闹3 小时前
基于java的改良版超级玛丽小游戏
java
Dream_Snowar3 小时前
速通Python 第三节
开发语言·python
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭3 小时前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
暮湫3 小时前
泛型(2)
java
超爱吃士力架4 小时前
邀请逻辑
java·linux·后端
南宫生4 小时前
力扣-图论-17【算法学习day.67】
java·学习·算法·leetcode·图论
转码的小石4 小时前
12/21java基础
java