Silentdoer

导航

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;

即可;

posted on 2020-12-23 16:58  Silentdoer  阅读(1261)  评论(1编辑  收藏  举报