公司有个项目使用了JDK17,需要访问外部的https服务的http get访问接口。
代码如下
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
简简单单的请求出现了以下错误,一脸懵.
查询了google,说是要下载证书到jre/lib/security下;
无奈mac的chrome及safari都无法导出证书;
只能自己研究看报错信息了, 主要错误原因在于新版本JDK的ssl验证报错:
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:439)
at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:306)
at java.base/sun.security.validator.Validator.validate(Validator.java:264)
at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:132)
at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:638)
... 24 more
因此只需要重写X509TrustManager, 并注入到httpClient即可
X509TrustManager可以自己实现,也可以使用现成实现,
比如cn.hutool.core.net.DefaultTrustManager
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new DefaultTrustManager();
ctx.init(null, new TrustManager[] { tm }, null);
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).build();
return httpclient;
使用该httpclient 执行就可以绕过ssl的证书检测。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。