关于使用Okhttp导致的证书信任问题

我们通常创建的方法使用的是这种,但有可能导致证书不受信任,访问不了的问题,比如调试运行时会报如下错误
OKHTTP javax.net.ssl.SSLHandshakeException
这时候我们不要着急,新建一个工具包,在包里新建如下类,类名随便取就行
package com.zy.community.utils;import okhttp3.OkHttpClient;import javax.net.ssl.*;/*** 处理证书不受信任的问题*/public class OkHttpSSL {//okHttp3添加信任所有证书public static OkHttpClient getUnsafeOkHttpClient() {try {final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {}@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {}@Overridepublic java.security.cert.X509Certificate[] getAcceptedIssuers() {return new java.security.cert.X509Certificate[]{};}}};final SSLContext sslContext = SSLContext.getInstance("SSL");sslContext.init(null, trustAllCerts, new java.security.SecureRandom());final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();OkHttpClient.Builder builder = new OkHttpClient.Builder();builder.sslSocketFactory(sslSocketFactory);builder.hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});return builder.build();} catch (Exception e) {throw new RuntimeException(e);}}}
紧接着我们把之前创建的方法替换为
OkHttpClient client = OkHttpSSL.getUnsafeOkHttpClient();
再次运行就不会报错了 。
【关于使用Okhttp导致的证书信任问题】感谢此大佬@哥哥是欧巴