javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed

异常信息

org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://xxx.xxx.com":  
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: 
unable to find valid certification path to requested target;

nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: 
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

业务场景

项目中,通过 RestTemplate 类去调用第三方https接口服务抛处的异常。

异常发生原因

第三发https服务是发布在外网上的,服务端用的ssl证书是自己生成的,本地没用安装此证书,导致抛出此异常。

解决方案

方案1 配置RestTemplate

  public RestTemplate sslRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
	//访问https服务,需要添加httpclient包,和如下配置
	TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

	SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
			.loadTrustMaterial(null, acceptingTrustStrategy)
			.build();

	SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

	CloseableHttpClient httpClient = HttpClients.custom()
			.setSSLSocketFactory(csf)
			.build();
	HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();

	factory.setHttpClient(httpClient);
	factory.setReadTimeout(3000);
	factory.setConnectTimeout(3000);
	RestTemplate restTemplate = new RestTemplate(factory);
	return restTemplate;
}

方案2 本地安装证书

stackoverflow安装证书解决方案

posted @ 2020-09-04 17:01  城南孔乙己  阅读(611)  评论(0)    收藏  举报