houzhongjian
2025-03-14 b0430a610332aca416ce8fa735b623650dfdac6c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>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<String,Object> headers, HttpRequest request) {
        for (Map.Entry entry : headers.entrySet()) {
            if (!entry.getKey().equals("Cookie")) {
                request.addHeader((String) entry.getKey(), (String) entry.getValue());
            } else {
                Map<String, Object> Cookies = (Map<String, Object>) 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> T httpPost(String url, String data, Map<String,Object> headers,Class<T> 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);
            }
        }
    }
}