shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package com.walker.remote.util;
 
import com.walker.remote.AbstractByteCoder;
import com.walker.remote.DoubleTrust;
import com.walker.remote.RemoteAccessor;
import com.walker.remote.RemoteAccessorException;
import com.walker.remote.support.DefaultRemoteAccessor;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.cookie.CookieStore;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.SocketConfig;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.util.Timeout;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
 
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
public class HttpUtils {
    
//    private Log logger = LogFactory.getLog(getClass());
 
    // http调用客户端
    private HttpClient httpClient = null;
//    private AbstractByteCoder contentCoder = null;
    
    private static HttpUtils httpUtils;
    
    private HttpUtils(){
//        beanFactory = new DefaultBeanFactory();
//        BeanFactoryHelper.setBeanFactory(beanFactory);
//        
//        httpClient = doCreateSafeHttpClient();
//        beanFactory.addBean(HttpClient.class, httpClient);
//        this.doCreateRemoteAccessor();
        httpClient = this.doCreateSafeHttpClient(null, null);
    }
    
    public static HttpUtils getInstance(){
        if(httpUtils == null){
            httpUtils = new HttpUtils();
        }
        return httpUtils;
    }
    
    public HttpClient getHttpClient() {
        return httpClient;
//        return doGetNewHttpClient();
    }
    
    /**
     * 返回设置过cookie的httpClient对象,每次都要新创建
     * 
     * @param cookieStore
     * @return
     */
    public HttpClient getHttpClientWithCookie(CookieStore cookieStore) {
//        return httpClient;
        return this.doCreateSafeHttpClient(null, cookieStore);
    }
    
    /**
     * 返回一个双向认证的<code>HttpClient</code>对象。</p>
     * 注意:在上层应用中,该方法通常被初始化调用,而不是每次使用都被频繁获取。
     * @param doubleTrust
     * @return
     */
    public HttpClient getHttpDoubleTrustClient(DoubleTrust doubleTrust, CookieStore cookieStore) {
        return  this.doCreateSafeHttpClient(doubleTrust, cookieStore);
//        try{
//            // 重新加入https信息
//            KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());
//            FileInputStream instream = new FileInputStream(new File(doubleTrust.getCerFilepath()));
//            //密匙库的密码
//            trustStore.load(instream, doubleTrust.getPassword().toCharArray());
//            //注册密匙库          
//            SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
//            //不校验域名
//            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
//            Scheme sch = new Scheme("https", 443, socketFactory);      
//            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
//            return httpClient;
//        } catch(Exception ex){
//            ex.printStackTrace();
//            return null;
//        }
    }
    
    /**
     * 创建线程安全的<code>HttpClient</code>对象。
     * @return
     */
    private HttpClient doCreateSafeHttpClient(DoubleTrust clientTrust, CookieStore cookieStore){
//        HttpParams params = new BasicHttpParams();
//        
//        //设置基本参数  
//        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
//        HttpProtocolParams.setContentCharset(params, StringUtils.DEFAULT_CHARSET_UTF8);  
//        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
//        
//        HttpConnectionParams.setStaleCheckingEnabled(params, false);
//        HttpConnectionParams.setTcpNoDelay(params, true);
//        HttpConnectionParams.setSocketBufferSize(params, 8 * 1024);
//        
//        HttpClientParams.setRedirecting(params, false);
//        
//        //超时设置  
//        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
//        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 15000);
//        // 该值就是连接不够用的时候等待超时时间,一定要设置,而且不能太大 ()
//        params.setLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, 500L);
//        // 在提交请求之前 测试连接是否可用
//        params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);
//        
//        //设置HttpClient支持HTTp和HTTPS两种模式  
//        SchemeRegistry schReg = new SchemeRegistry();  
////        schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));  
////        schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
//        schReg.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
//        try {
//            schReg.register(new Scheme("https", 443, getSSLSocketFactory(clientTrust)));
//        } catch (KeyManagementException e) {
//            e.printStackTrace();
//            throw new IllegalStateException("KeyManagementException: 创建ssl httpclient证书错误:" + e.getMessage());
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//            throw new IllegalStateException("NoSuchAlgorithmException: 创建ssl httpclient算法错误:" + e.getMessage());
//        } catch(FileNotFoundException ex){
//            throw new IllegalStateException("FileNotFoundException: 创建ssl失败未找到客户端证书:" + ex.getMessage());
//        } catch(Exception rex){
//            throw new IllegalStateException(rex);
//        }
//        
//        PoolingClientConnectionManager conMgr = new PoolingClientConnectionManager(schReg); 
//        conMgr.setDefaultMaxPerRoute(128); //每个主机的最大并行链接数   
//        conMgr.setMaxTotal(512);          //客户端总并行链接最大数
//        
//        HttpClient client = new DefaultHttpClient(conMgr, params); 
//        return client;
        CloseableHttpClient httpclient = null;
 
        //密匙库的密码
        InputStream instream = null;
        Resource resource = null;
        KeyStore keyStore = null;
        PoolingHttpClientConnectionManager cm = null;
        try {
            resource = new ClassPathResource(clientTrust.getCerFilepath());
            instream = resource.getInputStream();
            keyStore = KeyStore.getInstance("PKCS12");
//                instream = new FileInputStream(new File(clientTrust.getCerFilepath()));
//                keyStore.load(instream, clientTrust.getPassword().toCharArray());
            keyStore.load(instream, clientTrust.getPassword().toCharArray());
        } catch (Exception ex){
            throw new RemoteAccessorException("加载证书错误: " + clientTrust.getCerFilepath(), ex);
        }
 
        try {
            SSLContext sslcontext = SSLContexts.custom()
                    .loadKeyMaterial(keyStore, clientTrust.getPassword().toCharArray()).build();
 
            // Allow TLSv1 protocol only
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslcontext,
                    new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"},
                    null,
//                        SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
//                        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
                    new NoopHostnameVerifier()
            );
            //
            SocketConfig socketConfig = SocketConfig.custom()
                    .setSoTimeout(Timeout.ofSeconds(10))
                    .build();
 
            cm = PoolingHttpClientConnectionManagerBuilder.create()
                    .setDefaultSocketConfig(socketConfig)
                    .setSSLSocketFactory(sslsf).build();
            cm.setDefaultMaxPerRoute(128);
            cm.setMaxTotal(512);
        } catch (Exception ex){
            throw new RemoteAccessorException("SSLContext 异常: " + ex.getMessage(), ex);
        }
 
        if(clientTrust != null){
            try {
                httpclient = HttpClients.custom().setConnectionManager(cm).build();
                
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
                try {
                    instream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            if(cookieStore != null){
                httpclient = HttpClients.custom().setConnectionManager(cm).setDefaultCookieStore(cookieStore).build();
            } else {
                httpclient = HttpClients.custom().setConnectionManager(cm).build();
            }
        }
        return httpclient;
    }
    
//    private static SSLSocketFactory getSSLSocketFactory(DoubleTrust clientTrust) 
//            throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, FileNotFoundException{
//        SSLContext ctx = SSLContext.getInstance("TLSv1");
//        TrustManager[] trustManagers = null;
//        
//        if(clientTrust != null){
//            // 如果存在双向认证
//            // 重新加入https信息
//            KeyStore trustStore  = KeyStore.getInstance("PKCS12");
//            FileInputStream instream = new FileInputStream(new File(clientTrust.getCerFilepath()));
//            //密匙库的密码
//            try {
//                trustStore.load(instream, clientTrust.getPassword().toCharArray());
//            } catch (Exception e) {
//                e.printStackTrace();
//                throw new RuntimeException(e);
//            }
//            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");  
//            tmf.init(trustStore);
//            trustManagers = tmf.getTrustManagers();
//            
//        } else {
//            X509TrustManager tm = new X509TrustManager() {
//                @Override
//                public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
//                        throws java.security.cert.CertificateException {
//                    
//                }
//                
//                @Override
//                public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
//                        throws java.security.cert.CertificateException {
//                    
//                }
//                
//                @Override
//                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
//                    return null;
//                }
//            };
//            trustManagers = new TrustManager[]{tm};
//        }
//        
//        ctx.init(null, trustManagers, null);
//        return new SSLSocketFactory(ctx, SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
//    }
    
//    private HttpClient doGetNewHttpClient(){
//        HttpParams params = new BasicHttpParams();
//        
//        //设置基本参数  
//        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
//        HttpProtocolParams.setContentCharset(params, StringUtils.DEFAULT_CHARSET_UTF8);  
//        HttpProtocolParams.setUserAgent(params, "Android client");
//        
//        HttpConnectionParams.setStaleCheckingEnabled(params, false);
//        HttpConnectionParams.setTcpNoDelay(params, true);
//        HttpConnectionParams.setSocketBufferSize(params, 8 * 1024);
//        
//        HttpClientParams.setRedirecting(params, false);
//        /*连接超时*/  
//        HttpConnectionParams.setConnectionTimeout(params, 20000);  
//        /*请求超时*/  
//        HttpConnectionParams.setSoTimeout(params, 20000); 
//        HttpClient client = new DefaultHttpClient(params);  
//        return client;
//    }
    
    public static List<NameValuePair> doTranslatePairs(Map<String, String> simpleData){
        List<NameValuePair> pair = new ArrayList<NameValuePair>();
        for(Map.Entry<String, String> entry : simpleData.entrySet()){
            pair.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return pair;
    }
    
    /**
     * 把json格式参数转换为特定http参数
     * @param json
     * @return
     */
    public static List<NameValuePair> doTranslatePairs(String json){
        List<NameValuePair> pair = new ArrayList<NameValuePair>();
        pair.add(new BasicNameValuePair(RemoteAccessor.DEFALUT_FORM_DATA_NAME, json));
        return pair;
    }
    
    /**
     * 返回一个通用的远程访问对象
     * @param contentCoder
     * @return
     */
    public RemoteAccessor getNewRemoteAccessor(String remoteURL
            , AbstractByteCoder contentCoder, DoubleTrust doubleTrust){
//        String remoteURL = getRemoteServerURL();
        RemoteAccessor remoteAccessor = new DefaultRemoteAccessor();
        remoteAccessor.setBaseUrl(remoteURL);
        remoteAccessor.setContentEncoder(contentCoder);
        // 设置双向认证的客户端证书,如果存在
        remoteAccessor.setDoubleTrust(doubleTrust);
        return remoteAccessor;
    }
    
//    /**
//     * 添加远程请求单例对象。<br>
//     * 此方法放在<code>initialize()</code>方法之后,是因为需要子类先提供服务端访问URL地址,才能初始化该对象。
//     */
//    private void doCreateRemoteAccessor(){
//        String remoteURL = getRemoteServerURL();
//        logger.debug("............应用启动,获得一次RemoteURL: " + remoteURL);
//        contentCoder = new Base64ByteCoder();
//        RemoteAccessor remoteAccessor = new DefaultRemoteAccessor();
//        remoteAccessor.setBaseUrl(remoteURL);
//        remoteAccessor.setContentEncoder(contentCoder);
//    }
    
//    private String getRemoteServerURL(){
//        return "http://opentest.17wanxiao.com:80/campus/";
//        return "http://120.55.104.155:80/campus/";
//        return "http://www.17wanxiao.com/campus/";
//    }
}