忘记背后,努力面前的,向着标杆直跑
联系我:948870341@qq.com

原创

httpclient/RestTemplate,asynchttpclient设置忽略https,ssl证书

2018-05-13 22:08:44 rejoice 751 0
互联网与编程

1、全局设置(版本4.5)

static {  
        disableSslVerification();  
    }  
  
    private static void disableSslVerification() {  
        try{  
            // Create a trust manager that does not validate certificate chains  
            TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {  
                public X509Certificate[] getAcceptedIssuers() {  
                    return null;  
                }  
                public void checkClientTrusted(X509Certificate[] certs, String authType) {  
                }  
                public void checkServerTrusted(X509Certificate[] certs, String authType) {  
                }  
            }  
            };  
  
            // Install the all-trusting trust manager  
            SSLContext sc = SSLContext.getInstance("SSL");  
            sc.init(null, trustAllCerts, new java.security.SecureRandom());  
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
  
            // Create all-trusting host name verifier  
            HostnameVerifier allHostsValid = new HostnameVerifier() {  
                public boolean verify(String hostname, SSLSession session) {  
                    return true;  
                }  
            };  
  
            // Install the all-trusting host verifier  
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);  
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
        } catch (KeyManagementException e) {  
            e.printStackTrace();  
        }  
    }  

2、局部设置(版本:4.5)

RestTemplate restTemplate = new RestTemplate();  
        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {  
            @Override  
            public boolean isTrusted(X509Certificate[] arg0, String arg1)  
                    throws CertificateException {  
                return true;  
            }  
        };  
        SSLContext sslContext = SSLContexts.custom()  
                .loadTrustMaterial(null, acceptingTrustStrategy)  
                .build();  
                SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());  
          
                  
        Registry registry = RegistryBuilder.create()  
                .register("http", PlainConnectionSocketFactory.getSocketFactory())  
                .register("https", sf)  
                .build();  
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);  
        connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);  
        connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);  
        connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost("facebook.com")), 20);  
        connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost("twitter.com")), 20);  
        connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost("linkedin.com")), 20);  
        connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost("viadeo.com")), 20);  
        RequestConfig config = RequestConfig.custom().setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLISECONDS)  
                .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT_MILLISECONDS)  
                .setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_MILLISECONDS).build();  
          
  
        CloseableHttpClient defaultHttpClient = HttpClientBuilder.create().setConnectionManager(connectionManager)  
                .setRetryHandler(new DefaultHttpRequestRetryHandler(2, true))  
                .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE).setDefaultRequestConfig(config)  
                .build();  
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(  
                defaultHttpClient);  
        clientHttpRequestFactory.setBufferRequestBody(false);;  
        restTemplate.setRequestFactory(clientHttpRequestFactory );  

3、asynchttpclient(异步httpclient,版本:4.3)

@Bean  
    public AsyncClientHttpRequestFactory asyncHttpRequestFactory() {  
        HttpComponentsAsyncClientHttpRequestFactory asyncHttpRequestFactory = new HttpComponentsAsyncClientHttpRequestFactory(  
                asyncHttpClient());  
        asyncHttpRequestFactory.setBufferRequestBody(false);  
        return asyncHttpRequestFactory;  
    }  
  
    @Bean(name = "asyncRestTemplate")  
    public AsyncRestTemplate asyncRestTemplate() throws Exception {  
        AsyncRestTemplate restTemplate = new AsyncRestTemplate(asyncHttpRequestFactory(), restTemplate());  
        //restTemplate.setInterceptors(Arrays.asList(loggingClientHttpRequestInterceptor));  
        return restTemplate;  
    }  
  
    @Bean  
    public CloseableHttpAsyncClient asyncHttpClient() {  
        try {  
              
            //ssl support start  
            TrustStrategy acceptingTrustStrategy = new TrustStrategy() {  
                @Override  
                public boolean isTrusted(X509Certificate[] arg0, String arg1)  
                        throws CertificateException {  
                    return true;  
                }  
            };  
        SSLContext sslcontext = SSLContextBuilder.create()  
            .loadTrustMaterial(null, acceptingTrustStrategy )  
            .build();  
             Registry sessionStrategyRegistry = RegistryBuilder.create()  
                        .register("http", NoopIOSessionStrategy.INSTANCE)  
                        .register("https", new SSLIOSessionStrategy(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))  
                        .build();  
            PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(  
                    new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT),sessionStrategyRegistry);  
            connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);   
            connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);  
            connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost("facebook.com")), 20);  
            connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost("twitter.com")), 20);  
            connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost("linkedin.com")), 20);  
            connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost("viadeo.com")), 20);  
            RequestConfig config = RequestConfig.custom().setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLISECONDS)  
                    .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT_MILLISECONDS)  
                    .setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_MILLISECONDS).build();  
              
            CloseableHttpAsyncClient httpclient = HttpAsyncClientBuilder.create()  
                    .setConnectionManager(connectionManager)  
                    .setDefaultRequestConfig(config).build();  
            return httpclient;  
        } catch (Exception e) {  
            throw Throwables.propagate(e);  
        }  
    }