httpClient封装连接池发送https请求

@Slf4j
public class HttpUtils {


    private static final int MAX_TOTAL = 600;
    private static final int MAX_PER_ROUTE = 300;
    private static final int CONNECT_TIMEOUT = 5000;
    private static final int SOCKET_TIMEOUT = 5000;

    // 连接池管理器
    private static PoolingHttpClientConnectionManager connectionManager = null;
    private static  ResponseHandler<String> responseHandler;


    // 连接实例
    private static CloseableHttpClient httpClient;

    static {
        try {
            log.info("httpClient连接池初始化,连接池大小:{},每个路由最大连接数:{}", MAX_TOTAL, MAX_PER_ROUTE);
            //跳过SSL证书认证策略
            SSLConnectionSocketFactory sslFactory = createMySSLConnectionSocketFactory();
            // 配置同时支持 HTTP 和 HTTPS
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslFactory).build();
            // 创建连接池管理器对象
            connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            // 最大连接数
            connectionManager.setMaxTotal(MAX_TOTAL);
            // 每个路由最大连接数
            connectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE);
            // 初始化httpClient
            httpClient = createHttpClient();
            //初始化response解析器
            responseHandler = new BasicResponseHandler();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建HttpClient对象
     *
     * @return CloseableHttpClient
     */
    private static CloseableHttpClient createHttpClient() {
        if (httpClient == null) {
            log.info("初始化httpClient, 连接服务器超时时间:{}, 获取数据的超时时间:{}", CONNECT_TIMEOUT, SOCKET_TIMEOUT);
            RequestConfig defaultRequestConfig = RequestConfig.custom()
                    .setConnectTimeout(CONNECT_TIMEOUT) // 设置服务器超时时间
                    .setSocketTimeout(SOCKET_TIMEOUT) // 设定获取数据的超时时间
                    .build();

            httpClient = HttpClients.custom()
                    .setDefaultRequestConfig(defaultRequestConfig)
                    .setConnectionManager(connectionManager)
                    .setConnectionManagerShared(true)
                    .setRetryHandler(new DefaultHttpRequestRetryHandler(3,true))
                    //不用连接池需要设置这个
//                    .setSSLSocketFactory(sslConnectionSocketFactory)
//                .evictExpiredConnections()
                    .build();
        }
        return httpClient;
    }

    // 设置header
    private static <T extends HttpRequestBase> void setFullHeaders(T httpRequest, Map<String, String> addHeaders) {
        httpRequest.setHeader("Content-Type", "application/json");
        if (addHeaders.size() > 0) {
            for (String key : addHeaders.keySet()) {
                httpRequest.addHeader(key, addHeaders.get(key));
            }
        }
    }

    // Http协议Get请求
    public static String httpsGet(String url, Map<String, String> headers) throws Exception, HttpRequestException {
        CloseableHttpResponse response = null;
        String result = "";
        try {
            httpClient = createHttpClient();
            HttpGet httpGet = new HttpGet(url);
            //设置header
            setFullHeaders(httpGet, headers);
            //发起请求
            response = httpClient.execute(httpGet);
            //处理返回结果
            if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() > 300) {
                throw new HttpRequestException(result);
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
            httpGet.releaseConnection();
        } catch (Exception e) {
            e.printStackTrace();
            throw new HttpRequestException("httpclient IO error!", e);
        } finally {
            close(response);
        }
        return result;
    }

    // Http协议Post请求
    public static String httpsPost(String url, String json, Map<String, String> headers) throws HttpRequestException {
        CloseableHttpResponse response = null;
        String result = "";
        try {
            httpClient = createHttpClient();
            HttpPost httpPost = new HttpPost(url);
            //设置header
            setFullHeaders(httpPost, headers);
            //填充参数
            httpPost.setEntity(new StringEntity(json, "utf-8"));
            //发起请求
            return httpClient.execute(httpPost,responseHandler);
            //处理返回结果

        } catch (Exception e) {
            e.printStackTrace();
            throw new HttpRequestException("httpclient IO error!", e);
        }
    }

    // Http协议Put请求
    public static String httpsPut(String url, String body, Map<String, String> headers) throws HttpRequestException {
        CloseableHttpResponse response = null;
        String result = "";
        try {
            httpClient = createHttpClient();
            HttpPut httpRequest = new HttpPut(url);
            //设置header
            setFullHeaders(httpRequest, headers);
            //填充参数
            httpRequest.setEntity(new StringEntity(body, "utf-8"));
            //发起请求
            response = httpClient.execute(httpRequest);
            //处理返回结果
            if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() > 300) {
                throw new HttpRequestException(result);
            }
            //解析实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
            throw new HttpRequestException("httpclient IO error!", e);
        } finally {
            close(response);
        }
        return result;
    }

    // Http协议Delete请求
    public static String httpsDelete(String url, Map<String, String> headers) throws HttpRequestException {
        CloseableHttpResponse response = null;
        String result = "";
        try {
            httpClient = createHttpClient();
            HttpDelete httpRequest = new HttpDelete(url);
            //设置header
            setFullHeaders(httpRequest, headers);
            //发起请求
            response = httpClient.execute(httpRequest);
            //处理返回结果
            if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() > 300) {
                throw new HttpRequestException(result);
            }
            HttpEntity entity = response.getEntity();
            //返回结果可能为空
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
            throw new HttpRequestException("httpclient IO error!", e);
        } finally {
            close(response);
        }
        return result;
    }

    //创建一个跳过SSL证书认证策略的简单连接
    public static CloseableHttpClient createSSLClientDefault() throws Exception {
        //信任所有
        SSLContext sslcontext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }

    // 跳过SSL证书认证策略
    private static SSLConnectionSocketFactory createMySSLConnectionSocketFactory() throws Exception {
        SSLContext sslcontext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();
        return new SSLConnectionSocketFactory(sslcontext);
    }


    /**
     * 关闭CloseableHttpResponse对象
     *
     * @param response CloseableHttpResponse对象
     */
    private static void close(CloseableHttpResponse response) {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpClientExample {
    public static void main(String[] args) {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        // 设置空闲持久连接在被视为陈旧之前的空闲时间(单位为毫秒)
        cm.setValidateAfterInactivity(2000);

        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .build();

        // 使用httpClient...
    }
}

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpClient是一个非常常用的HTTP客户端库,可以用于发送HTTP请求并接收响应。在封装HttpClient时,我们可以考虑以下几点: 1. 连接池管理:HttpClient可以通过连接池来管理HTTP连接,从而提高性能。我们可以设置最大连接数、每个路由的最大连接数等参数,以便更好地利用连接池。 2. 超时设置:在发送HTTP请求时,我们需要设置超时时间,以避免请求过程中出现阻塞或超时等问题。可以设置连接超时时间、读取超时时间等参数。 3. 异常处理:在发送HTTP请求时,可能会出现各种异常情况,例如网络异常、连接超时等。我们需要对这些异常进行处理,以便及时发现问题并进行处理。 4. 请求头设置:在发送HTTP请求时,我们需要设置请求头,以便服务器能够正确地处理请求。可以设置User-Agent、Content-Type等参数。 5. SSL支持:如果需要发送HTTPS请求,则需要支持SSL协议。可以通过配置SSLContext来实现SSL支持。 下面是一个简单的HttpClient封装示例: ```java public class HttpClientUtil { private static final int MAX_TOTAL = 200; private static final int MAX_PER_ROUTE = 50; private static final int CONNECT_TIMEOUT = 5000; private static final int SOCKET_TIMEOUT = 10000; private static CloseableHttpClient httpClient; static { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(MAX_TOTAL); cm.setDefaultMaxPerRoute(MAX_PER_ROUTE); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(CONNECT_TIMEOUT) .setSocketTimeout(SOCKET_TIMEOUT) .build(); httpClient = HttpClients.custom() .setConnectionManager(cm) .setDefaultRequestConfig(requestConfig) .build(); } public static String doGet(String url, Map<String, String> headers) throws IOException { HttpGet httpGet = new HttpGet(url); if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpGet.setHeader(entry.getKey(), entry.getValue()); } } try (CloseableHttpResponse response = httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } } return null; } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值