All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gitee.summer9102.develop.common.httpclient.HttpClientUtil Maven / Gradle / Ivy

There is a newer version: 1.1.0
Show newest version
package com.gitee.summer9102.develop.common.httpclient;

import org.apache.http.Consts;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

/**
 * 集成HTTP连接池
 * 网络请求工具
 */
public class HttpClientUtil {

    //发送请求的客户端单例
    private volatile CloseableHttpClient httpClient;
    //连接池管理器
    private PoolingHttpClientConnectionManager connectionManager;
    //请求设置
    private RequestConfig requestConfig;
    //相当于线程锁,用于线程安全
    private final static Object syncLock = new Object();

    public HttpClientUtil(int httpMaxPoolSize, int connectTimeout, int socketTimeout, int maxIdleTime) {
        try {
            Registry socketFactoryRegistry = RegistryBuilder.create()
                    .register("https", new SSLConnectionSocketFactory(SSLContext.getDefault()))
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .build();
            connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            // 最大连接数
            connectionManager.setMaxTotal(httpMaxPoolSize);
            // 路由最大连接数
            connectionManager.setDefaultMaxPerRoute(httpMaxPoolSize);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        requestConfig = RequestConfig.custom()
                // 获取连接超时时间
                .setConnectionRequestTimeout(connectTimeout)
                // 连接建立超时时间
                .setConnectTimeout(connectTimeout)
                // 获取数据超时时间
                .setSocketTimeout(socketTimeout)
                .build();

        httpClient = initHttpClient(maxIdleTime);
    }

    private CloseableHttpClient initHttpClient(int maxIdleTime) {
        return HttpClients.custom()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(requestConfig)
                //清理超过空闲时间的连接
                .evictIdleConnections(maxIdleTime > 0 ? maxIdleTime : 30000, TimeUnit.MILLISECONDS)
                .build();
    }

    public CloseableHttpClient getHttpClient() {
        if (httpClient == null) {
            synchronized (syncLock) {
                if (httpClient == null) {
                    httpClient = initHttpClient(30000);
                }
            }
        }
        return httpClient;
    }

    public String requestToString(HttpUriRequest request) {
        String result = null;
        CloseableHttpResponse response = null;
        try {
            //开启HttpClient
            response = getHttpClient().execute(request);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }

            return result;
        } catch (Exception e) {
            return null;
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }

    public byte[] requestToByteArray(HttpUriRequest request) {
        byte[] result = null;
        CloseableHttpResponse response = null;
        try {
            //开启HttpClient
            response = getHttpClient().execute(request);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toByteArray(response.getEntity());
            }

            return result;
        } catch (Exception e) {
            return null;
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy