不要被这个世界改变!|

HttpClient

apache httpclient 带连接池
这本来是个分享的,但插件不好使了,等有时间在搞一个
 
						package com.zhongan.app.subao.keystone.util;
  
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
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.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
  
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class HttpClientUtil {
  
    private static Logger LOG = LoggerFactory.getLogger(HttpClientUtil.class);
  
    private static CloseableHttpClient httpClient;
  
    static {
        try {
            // ------------------
            SSLContext sslContext = SSLContexts.custom()
                    .loadTrustMaterial(new TrustStrategy() {
                        public boolean isTrusted(X509Certificate[] chain,
                                                 String authType) throws CertificateException {
                            return true;
                        }
                    }).build();
  
            ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.INSTANCE;
            LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslContext, NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder
                    .<ConnectionSocketFactory>create().register("http", plainsf)
                    .register("https", sslsf).build();
            // ------------------
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
                    registry);
            connManager.setMaxTotal(256);
            connManager.setDefaultMaxPerRoute(50);
            // ------------------
            RequestConfig.Builder builder_conf = RequestConfig.custom();
            builder_conf.setConnectionRequestTimeout(30000);
            builder_conf.setConnectTimeout(30000);
            builder_conf.setSocketTimeout(60000);
  
            HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(
                    3, true);
            // ------------------
            HttpClientBuilder builder = HttpClients.custom();
            builder.setSSLContext(sslContext);
            builder.setConnectionManager(connManager);
            builder.setDefaultRequestConfig(builder_conf.build());
            builder.setRetryHandler(retryHandler);
            // ------------------
  
            httpClient = builder.build();
        } catch (Exception e) {
            LOG.error(ExceptionUtils.getStackTrace(e));
        }
    }
  
    public static String httpGet(String url, Map<String, String> headers, BasicClientCookie cookie) {
        HttpGet httpGet = new HttpGet(url);
        if (headers != null) {
            headers.forEach((k, v) -> {
                httpGet.addHeader(k, v);
            });
        }
        try {
            HttpContext httpContext = createHttpContext(cookie);
            if (null != httpContext) {
                return processResponse(httpClient.execute(httpGet, httpContext));
            } else {
                return processResponse(httpClient.execute(httpGet));
            }
        } catch (Exception e) {
            LOG.error("GET : " + url + " ERROR", e);
        }
        return null;
    }
  
    public static String httpPost(String url, Map<String, String> params) {
        return httpPost(url, params, null, null);
    }
  
    public static String httpGet(String url) {
        return httpGet(url, null, null);
    }
  
    public static String httpPost(String url, Map<String, String> params, Map<String, String> headers, BasicClientCookie cookie) {
        HttpPost httpPost = new HttpPost(url);
        if (headers != null) {
            headers.forEach((k, v) -> {
                httpPost.addHeader(k, v);
            });
        }
  
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if (params != null) {
            Set<String> keySet = params.keySet();
            for (String key : keySet) {
                nvps.add(new BasicNameValuePair(key, params.get(key)));
            }
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            HttpContext httpContext = createHttpContext(cookie);
            if (null != httpContext) {
                return processResponse(httpClient.execute(httpPost, httpContext));
            } else {
                return processResponse(httpClient.execute(httpPost));
            }
        } catch (Exception e) {
            LOG.error("POST : " + url + " ERROR", e);
        }
        return null;
    }
  
    private static HttpContext createHttpContext(BasicClientCookie cookie) {
        if (cookie != null) {
            HttpContext localContext = new BasicHttpContext();
            CookieStore cookieStore = new BasicCookieStore();
            cookieStore.addCookie(cookie);
            localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
            return localContext;
        }
        return null;
    }
  
    private static String processResponse(HttpResponse httpResponse) throws IOException {
        if (httpResponse != null) {
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = httpResponse.getEntity();
                return EntityUtils.toString(entity, Charset.forName("UTF-8"));
            }
        }
        return null;
    }
  
}
						//该片段来自于http://www.codesnippet.cn/detail/2906201815282.html