让okhttp信任所有证书,采用的是忽略https认证,自己构建一个x509认证,默认通过,再传到ssl配置工厂中,再用okhttpclient发送请求的时候就不会再报证书错误
public OkHttp() {
client = new OkHttpClient.Builder()
.sslSocketFactory(MySSLSocketClient.getSSLSocketFactory(),MySSLSocketClient.getX509TrustManager()) // //通过sslSocketFactory方法设置https证书
.hostnameVerifier(MySSLSocketClient.getHostnameVerifier())
.build();
}
package test;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class TestSSLSocketClient {
//获取SSLSocketFactory
public static SSLSocketFactory getSSLSocketFactory() {
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, getTrustManager(), new SecureRandom());
return sslContext.getSocketFactory();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//获取TrustManager
private static TrustManager[] getTrustManager() {
TrustManager[] trustAllCerts = new TrustManager[]{
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[]{};
}
}
};
return trustAllCerts;
}
//获取HostnameVerifier,验证主机名
public static HostnameVerifier getHostnameVerifier() {
HostnameVerifier hostnameVerifier = (s, sslSession) -> true;
return hostnameVerifier;
}
//X509TrustManager:证书信任器管理类
public static X509TrustManager getX509TrustManager() {
X509TrustManager x509TrustManager = 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[0];
}
};
return x509TrustManager;
}
}
版权声明:本文为dingding_ting原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。