问题
我们在和第三方系统交互时,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;
/**
*
* @author Jeter
*
*/
public class OkHttpUtil {
/**
* X509TrustManager instance which ignored SSL certification
*/
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[] {};
}
};
/**
* Get initialized SSLContext instance which ignored SSL certification
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
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;
}
/**
* Get HostnameVerifier which ignored SSL certification
*
* @return
*/
public static HostnameVerifier getIgnoreSslHostnameVerifier() {
return new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
};
}
}
然后我们之前有提到,只忽略目标Url。所以我们在创建 OkHttp Clent的地方引用工具类即可文章来源:https://www.toymoban.com/news/detail-700703.html
OkHttpClient client = new OkHttpClient.Builder()
.sslSocketFactory(OkHttpUtil.getIgnoreInitedSslContext().getSocketFactory(),OkHttpUtil.IGNORE_SSL_TRUST_MANAGER_X509)
.hostnameVerifier(OkHttpUtil.getIgnoreSslHostnameVerifier())
.build();
总结
最后测试通过不在遇到SSL证书验证问题。忽略证书验证可以作为兜底方案,有感兴趣的大佬可以研究添加证书,无疑才是最正规的解决方案。文章来源地址https://www.toymoban.com/news/detail-700703.html
到了这里,关于Java okHttp 忽略Https证书验证的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!