项目场景:
访问HTTPS协议的 api
报错
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilder
和
Certificate for <xxx.xxx.xxx.xxx> doesn’t match any of the subject alternative names: []
问题一
使用Java访问https协议的api报错
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilder.
原因分析:
需要配置SSL证书或者绕开ssl
解决方案:
使用浏览器访问一下api路径,然后点击左边框下载证书
将证书导出
进入jdk home path下的的lib下的secruity目录,导入证书
cd C:\Tools\Java\jre\lib\security
keytool -import -alias cn -keystore cacerts -file C:\Tools\Java\jre\lib\security\cn.crt
输入默认密码导入证书
changeit
y
如图所示:
问题二
导入证书后报错:
Certificate for <xxx.xxx.xxx.xxx> doesn’t match any of the subject alternative names: []
javax.net.ssl.SSLPeerUnverifiedException: Certificate for <xxx.xxx.xxx.xxx> doesn't match any of the subject alternative names: []
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.verifyHostname(SSLConnectionSocketFactory.java:507)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:437)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:384)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:376)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
at com.apig.sdk.demo.Main.main(Main.java:61)
解决方案:
修改添加如下代码:
SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(
SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
NoopHostnameVerifier.INSTANCE);
client = HttpClients.custom().setSSLSocketFactory(scsf).build();