欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RestTemplate忽略https证书认证

程序员文章站 2022-05-31 16:10:02
...

 

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;
}