1.在使用Glide前调用
Glide.get(this).getRegistry().replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(getNoCheckOkHttpClient()));
2.getNoCheckOkHttpClient方法如下
public static OkHttpClient getNoCheckOkHttpClient() { SSLSocketFactory ssl = getNoCheckSSLSocketFactory(); X509TrustManager trustManager = getTrustManager(); return new OkHttpClient.Builder() .connectTimeout(TimeUnit.SECONDS.toMillis(30), TimeUnit.SECONDS) .readTimeout(TimeUnit.SECONDS.toMillis(30), TimeUnit.SECONDS) .writeTimeout(TimeUnit.SECONDS.toMillis(30), TimeUnit.SECONDS) .sslSocketFactory(ssl, trustManager) .hostnameVerifier((hostname, session) -> true) .retryOnConnectionFailure(true) .build(); }
public static SSLSocketFactory getNoCheckSSLSocketFactory() { try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[] {getTrustManager()}, new SecureRandom()); return sslContext.getSocketFactory(); } catch (Exception e) { throw new RuntimeException(e); } }
/** * 获得信任管理器TrustManager,不做任何校验 * * @return X509TrustManager */ public static X509TrustManager getTrustManager() { return new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] serverX509Certificates, String s) {} /** * 只支持正序或者逆序存放的证书链,如果证书链顺序打乱的将不支持 我们以下认定x509Certificates数组里从0-end如果是设备证书到ca root证书是正序的 * 反之是倒序的 */ @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {} @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; }