SpringBoot用restTemplate调用https接口报 sun.security.validator.ValidatorException: PKIX path 。。。


修改自:http://blog.joylau.cn/2020/10/19/SpringBoot-RestTemplate-SSL/

解决办法是写一个@Configuration配置类,里面添加代码:

import org.apache.http.conn.ssl.NoopHostnameVerifier;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.ssl.SSLContextBuilder;


    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplateBuilder.build();
    }

    /**
     * HTTPS RestTemplate
     */
    @Bean
    public RestTemplate httpsRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);

        CloseableHttpClient httpClient
                = HttpClients.custom()
                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .setSSLSocketFactory(sslConnectionSocketFactory)
                .build();
        HttpComponentsClientHttpRequestFactory requestFactory
                = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        requestFactory.setConnectTimeout((int)Duration.ofSeconds(5).toMillis());
        return new RestTemplate(requestFactory);
    }

然后用的地方由原来的:

@Resource
private RestTemplate restTemplate;

改成:

@Resource
private RestTemplate httpsRestTemplate;

即可;


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM