修复 Caused by: sun.security.validator.ValidatorException: PKIX path building failed 异常

这个问题的异常信息,其实很长,标题中我只截取了一部分。如果全部列取出来,我估计会影响搜索引擎的收录。

下面这个才是完整的异常信息。

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

出现这个错误的原因是 https 加密过程中,证书验证没通过。按照我下面的代码调整一下,就可以解决掉这个错误!

public class HttpClientUtils {
    public static CloseableHttpClient acceptsUntrustedCertsHttpClient() throws KeyStoreException, 
            NoSuchAlgorithmException, KeyManagementException {
        HttpClientBuilder b = HttpClientBuilder.create();
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy(){
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) {
                return false;
            }
        }).build();
        b.setSSLContext(sslContext);
        HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry);
        connMgr.setMaxTotal(200);
        connMgr.setDefaultMaxPerRoute(100);
        b.setConnectionManager( connMgr);
        CloseableHttpClient client = b.build();
        return client;
    }
}

RestTemplate 再调整一下!

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate httpsRestTemplate(HttpComponentsClientHttpRequestFactory httpsFactory) {
        RestTemplate restTemplate = new RestTemplate(httpsFactory);
        restTemplate.setErrorHandler(
                new ResponseErrorHandler() {
                    public boolean hasError(ClientHttpResponse clientHttpResponse) {
                        return false;
                    }
                    public void handleError(ClientHttpResponse clientHttpResponse) {
                        // 默认处理非200的返回,会抛异常
                    }
                });
        return restTemplate;
    }
    @Bean(name = "httpsFactory")
    public HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory()
            throws Exception {
        CloseableHttpClient httpClient = HttpClientUtils.acceptsUntrustedCertsHttpClient();
        HttpComponentsClientHttpRequestFactory httpsFactory =
                new HttpComponentsClientHttpRequestFactory(httpClient);
        httpsFactory.setReadTimeout(40000);
        httpsFactory.setConnectTimeout(40000);
        return httpsFactory;
    }
}

最后测试代码如下:

@RunWith(SpringRunner.class)
@SpringBootTest
public class RestTemplateTest {
    @Autowired
    private RestTemplate restTemplate;
    @Test
    public void testHttps(){
        String url = "https://free-api.heweather.com/v5/forecast?city=CN101080101&key=5c043b56de9f4371b0c7f8bee8f5b75e";
        String resp = restTemplate.getForObject(url, String.class);
        System.out.println(resp);
    }
}

最后 Maven 中需要引入一下配置:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>

这样就可以做到,RestTemplate 发送 HTTP、HTTPS 请求了!

修复 Caused by: sun.security.validator.ValidatorException: PKIX path building failed 异常

: » 修复 Caused by: sun.security.validator.ValidatorException: PKIX path building failed 异常

原创文章,作者:wure,如若转载,请注明出处:https://blog.ytso.com/252160.html

(0)
上一篇 2022年5月4日
下一篇 2022年5月4日

相关推荐

发表回复

登录后才能评论