问题
我们在和第三方系统交互时,Https url会出现找不到证书的问题。unable to find valid certification path to requested target.
我尝试过很多方法比如添加证书等,但是最后都以失败告终。只能退而求其次忽略指定url的证书验证,亲测好用!
解决方案
创建OkHttpUtil类,代码如下:
import lombok.var;import javax.net.ssl.*;import java.security.KeyManagementException;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.security.cert.X509Certificate;public class OkHttpUtil { public static final X509TrustManager IGNORE_SSL_TRUST_MANAGER_X509 = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } }; public static SSLContext getIgnoreInitedSslContext() throws NoSuchAlgorithmException, KeyManagementException { var sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[] { IGNORE_SSL_TRUST_MANAGER_X509 }, new SecureRandom()); return sslContext; } public static HostnameVerifier getIgnoreSslHostnameVerifier() { return new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }; }}
然后我们之前有提到,只忽略目标Url。所以我们在创建 OkHttp Clent的地方引用工具类即可
OkHttpClient client = new OkHttpClient.Builder().sslSocketFactory(OkHttpUtil.getIgnoreInitedSslContext().getSocketFactory(),OkHttpUtil.IGNORE_SSL_TRUST_MANAGER_X509).hostnameVerifier(OkHttpUtil.getIgnoreSslHostnameVerifier()).build();
总结
最后测试通过不在遇到SSL证书验证问题。忽略证书验证可以作为兜底方案,有感兴趣的大佬可以研究添加证书,无疑才是最正规的解决方案。
来源地址:https://blog.csdn.net/zjt11112/article/details/131082249