RestTemplate忽略https证书认证

阅读更多

 

public static RestTemplate buildRestTemplate() {

    RestTemplate restTemplate = new RestTemplate();
    if (ignoreSSL) {//ignoreSSL为true时,绕过证书
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectionRequestTimeout(300000);
        factory.setConnectTimeout(300000);
        factory.setReadTimeout(300000);
        // https
        CloseableHttpClient httpClient = getHttpsClient();
        factory.setHttpClient(httpClient);
        restTemplate = new RestTemplate(factory);
    }
    reInitMessageConverter(restTemplate);
    return restTemplate;
}

public static CloseableHttpClient getHttpsClient() {

    CloseableHttpClient httpClient;
    if (ignoreSSL) {//ignoreSSL为true时,绕过证书
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();
        } catch (NoSuchAlgorithmException e) {
            e.getStackTrace();
        } catch (KeyManagementException e) {
            e.getStackTrace();
        } catch (KeyStoreException e) {
            e.getStackTrace();
        }
        httpClient = HttpClients.custom().setSSLContext(sslContext).
                setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    } else {
        httpClient = HttpClients.createDefault();
    }
    return httpClient;
}

你可能感兴趣的:(RestTemplate,https,绕开证书)