Spring Boot RestTemplate 绕过HTTPS证书验证

开发中,搭建的HTTPS协议的接口地址很多是没有证书的。对接这样的接口我们只能绕过证书验证。
Spring Boot RestTemplate 绕过证书验证访问HTTPS接口:

    @Bean
    public RestTemplate buildRestTemplate(List interceptors) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpComponentsClientHttpRequestFactory factory = new                                                    
        HttpComponentsClientHttpRequestFactory();
    factory.setConnectionRequestTimeout(requestTimeout);
    factory.setConnectTimeout(connectTimeout);
    factory.setReadTimeout(readTimeout);
    // https
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, (X509Certificate[] x509Certificates, String s) -> true);
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
    Registry registry = RegistryBuilder.create()
            .register("http", new PlainConnectionSocketFactory())
            .register("https", socketFactory).build();
    PoolingHttpClientConnectionManager phccm = new PoolingHttpClientConnectionManager(registry);
    phccm.setMaxTotal(200);
    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).setConnectionManager(phccm).setConnectionManagerShared(true).build();
    factory.setHttpClient(httpClient);

    RestTemplate restTemplate = new RestTemplate(factory);
    List clientInterceptorList = new ArrayList<>();
    for (CustomHttpRequestInterceptor i : interceptors) {
        ClientHttpRequestInterceptor interceptor = i;
        clientInterceptorList.add(interceptor);
    }
    restTemplate.setInterceptors(clientInterceptorList);
    
    return restTemplate;
}

你可能感兴趣的:(Spring Boot RestTemplate 绕过HTTPS证书验证)