package com.iailab.sdk.util.http; import com.alibaba.fastjson.JSON; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpStatus; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; 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.conn.ssl.TrustSelfSignedStrategy; 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.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicHeader; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import java.io.Closeable; import java.io.IOException; import java.util.Map; public class HttpClientFactory { private static final Logger logger = LoggerFactory.getLogger(HttpClientFactory.class); private static PoolingHttpClientConnectionManager clientConnectionManager=null; // private static CloseableHttpClient httpClient=null; private static RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build(); // private final static Object syncLock = new Object(); private static boolean isInited=false; /** * 创建httpclient连接池并初始化 */ private static void init(){ if(isInited)return; try { //添加对https的支持,该sslContext没有加载客户端证书 // 如果需要加载客户端证书,请使用如下sslContext,其中KEYSTORE_FILE和KEYSTORE_PASSWORD分别是你的证书路径和证书密码 //KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType() //FileInputStream instream = new FileInputStream(new File(KEYSTORE_FILE)); //keyStore.load(instream, KEYSTORE_PASSWORD.toCharArray()); //SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keyStore,KEYSTORE_PASSWORD.toCharArray()) // .loadTrustMaterial(null, new TrustSelfSignedStrategy()) //.build(); SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.getDefaultHostnameVerifier()); Registry socketFactoryRegistry = RegistryBuilder.create() .register("https", sslsf) .register("http", PlainConnectionSocketFactory.getSocketFactory()) .build(); clientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); clientConnectionManager.setMaxTotal(50); clientConnectionManager.setDefaultMaxPerRoute(25); isInited=true; }catch (Exception e){ logger.warn("httpUtils init get exception:",e); } } public static CloseableHttpClient getHttpClient(){ init(); // if(httpClient == null){ // synchronized (syncLock){ // if(httpClient == null){ //// CookieStore cookieStore = new BasicCookieStore(); //// BasicClientCookie cookie = new BasicClientCookie("sessionID", "######"); //// cookie.setDomain("#####"); //// cookie.setPath("/"); //// cookieStore.addCookie(cookie); // httpClient =HttpClients.custom().setConnectionManager(clientConnectionManager) // //.setDefaultCookieStore(cookieStore) // .setDefaultRequestConfig(config).build(); // } // } // } // return httpClient; return HttpClients.custom().setConnectionManager(clientConnectionManager) //.setDefaultCookieStore(cookieStore) .setDefaultRequestConfig(config).build(); } /** * 设置请求头信息 * @param headers * @param request * @return */ private static HttpRequest setHeaders(Map headers, HttpRequest request) { for (Map.Entry entry : headers.entrySet()) { if (!entry.getKey().equals("Cookie")) { request.addHeader((String) entry.getKey(), (String) entry.getValue()); } else { Map Cookies = (Map) entry.getValue(); for (Map.Entry entry1 : Cookies.entrySet()) { request.addHeader(new BasicHeader("Cookie", (String) entry1.getValue())); } } } return request; } /** * post请求,使用json格式传参 * @param url * @param data * @param headers * @return */ public static T httpPost(String url, String data, Map headers,Class clazz){ CloseableHttpClient httpClient = getHttpClient(); HttpRequest request = new HttpPost(url); if(headers!=null&&!headers.isEmpty()){ request = setHeaders(headers,request); } CloseableHttpResponse response = null; try { HttpPost httpPost = (HttpPost) request; httpPost.setEntity(new StringEntity(data, ContentType.create("application/json", "UTF-8"))); response=httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode() && null != entity) { String respBody = EntityUtils.toString(entity); logger.info("validate st response:"+respBody); T respObj = (T) JSON.parseObject(respBody, clazz); return respObj; } } catch (IOException e) { logger.error("http post exec error,msg"+e.getMessage(),e); } finally { safeClose(response,null); // safeClose(httpClient,null); } return null; } private static void safeClose(Closeable closeable,String errMsg){ try{ if(closeable!=null) closeable.close(); }catch (Exception ex){ if(errMsg!=null && "".equals(errMsg)){ logger.error(errMsg+",error:"+ex.getMessage(),ex); } } } }