httpclient工具类
博客专区 > HdPang 的博客 > 博客详情
httpclient工具类
HdPang 发表于2年前
httpclient工具类
  • 发表于 2年前
  • 阅读 17
  • 收藏 0
  • 点赞 0
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   

工作中整理的一个基于httpclient4.3.4 的工具类

import com.google.common.base.Optional;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HttpClient4Util {
    private final static Logger logger = LoggerFactory
            .getLogger(HttpClient4Util.class);
    private CloseableHttpClient httpclient;
    private RequestConfig requestConfig;
    private PoolingHttpClientConnectionManager connManager;
    private static HttpClient4Util httpClient4UtilNew;
    private volatile boolean shutdown;

    public synchronized static HttpClient4Util getInstance() throws Exception {
        if (httpClient4UtilNew == null) {
            httpClient4UtilNew = new HttpClient4Util();
            httpClient4UtilNew.init();
        }
        return httpClient4UtilNew;
    }

    private HttpClient4Util() {

    }

    /**
     * 构造函数
     */
    public void init() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslCtx = SSLContext.getInstance("TLS");
        X509TrustManager trustManager = new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                    throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                    throws CertificateException {
            }
        };
        sslCtx.init(null, new TrustManager[]{trustManager}, null);
        LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslCtx, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
                .<ConnectionSocketFactory>create();
        ConnectionSocketFactory plainSocketFactory = new PlainConnectionSocketFactory();
        registryBuilder.register("http", plainSocketFactory);
        registryBuilder.register("https", sslSocketFactory);

        Registry<ConnectionSocketFactory> registry = registryBuilder.build();
        // 设置连接管理器
        connManager = new PoolingHttpClientConnectionManager(registry);
        // 设置最大连接数
        connManager.setMaxTotal(200);
        // 设置每个路由基础的连接
        connManager.setDefaultMaxPerRoute(20);

        // 连接保持活跃策略
        ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
            @Override
            public long getKeepAliveDuration(HttpResponse response,
                                             HttpContext context) {
                // 获取'keep-alive'HTTP报文头
                HeaderElementIterator it = new BasicHeaderElementIterator(
                        response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (null != value && "timeout".equalsIgnoreCase(param)) {
                        try {
                            return Long.parseLong(value) * 1000;
                        } catch (NumberFormatException ignore) {
                        }
                    }
                }
                // 保持20秒活跃
                return 20 * 1000;
            }
        };

        httpclient = HttpClientBuilder.create().setConnectionManager(
                connManager).setKeepAliveStrategy(myStrategy).build();
        shutdown = false;

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!shutdown) {
                    try {
                        synchronized (this) {
                            wait(500);
                            // 关闭过期的连接
                            connManager.closeExpiredConnections();
                            // 关闭超过40秒的空闲连接
                            connManager.closeIdleConnections(40, TimeUnit.SECONDS);
                        }
                    } catch (Exception e) {
                        logger.error(e.getLocalizedMessage(), e);
                    }
                }
            }
        }).start();
    }

    /**
     * 基本的Get请求
     *
     * @param url            请求URL
     * @param nameValuePairs 请求List<NameValuePair>查询参数
     */
    public byte[] doGet(String url, List<NameValuePair> nameValuePairs) {
        CloseableHttpResponse response = null;
        HttpGet httpget = new HttpGet();
        try {
            URIBuilder builder = new URIBuilder(url);
            // 填入查询参数
            if (nameValuePairs != null && !nameValuePairs.isEmpty()) {
                builder.setParameters(nameValuePairs);
            }
            httpget.setURI(builder.build());
            httpget.setConfig(requestConfig);
            response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toByteArray(entity);
            }
        } catch (Exception e) {
            logger.error("http 请求异常", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("释放连接异常", e);
                }
            }
        }
        return null;
    }

    /**
     *
     * @param url
     * @param queryParams
     * @param formParams
     * @return
     */
    public byte[] doPost(String url, Map<String, String> heard, List<NameValuePair> queryParams, List<NameValuePair> formParams, String content, int timeout) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        CloseableHttpResponse response = null;
        HttpPost httppost = new HttpPost();
        try {
            URIBuilder builder = new URIBuilder(url);
            // 填入查询参数
            if (CollectionUtils.isNotEmpty(queryParams)) {
                builder.setParameters(queryParams);
            }
            httppost.setURI(builder.build());
            timeout = Optional.fromNullable(timeout).or(60000);
            requestConfig = RequestConfig.custom()
                    .setConnectTimeout(timeout).setSocketTimeout(
                            timeout).build();
            httppost.setConfig(requestConfig);
            if (null != heard) {
                for (String key : heard.keySet()) {
                    httppost.setHeader(key, heard.get(key));
                }
            }

            if (CollectionUtils.isNotEmpty(formParams)) {
                httppost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
            }
            if (StringUtils.isNotBlank(content)) {
                httppost.setEntity(new StringEntity(content, "UTF-8"));
            }
            response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            int stateCode = response.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK != stateCode) {
                logger.error("非正常响应[" + stateCode + "]", new String(EntityUtils.toByteArray(entity), "UTF-8"));
                return null;
            }
            if (entity != null) {
                return EntityUtils.toByteArray(entity);
            }
        } catch (Exception e) {
            logger.error("http请求异常", e);
        } finally {
            httppost.releaseConnection();
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("释放连接异常", e);
                }
            }
        }
        return null;
    }

}
  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 0
博文 5
码字总数 1581
×
HdPang
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: