之前项目中一直用的Glide加载服务器图片,突然运维换了证书,就莫名其妙的图片不显示了,紧急修复,网上很多资料,忽略证书,但是网上的资料原封不动设置完成之后,5.0之后没有问题,完美修复。谁知有一测试机4.4的,死活显示不出来,最后如下解决,目前测试4.4及5.0以上均显示。
1.在Application中进行初始化,主要是获取一个忽略证书的okhttpClient,也可在其他地方初始化。
Glide.get(this).register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(getOkHttpClient ()));
2.
public OkHttpClient getOkHttpClient () {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
X509Certificate[] x509Certificates = new X509Certificate[0];
return x509Certificates;
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setSslSocketFactory(sslSocketFactory);
okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
okHttpClient.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
或者:(参数可不传)
public static OkHttpClient getOkHttpClient(InputStream... certificates)
{
SSLSocketFactory sslSocketFactory = HttpsUtils.getSslSocketFactory(certificates, null, null);
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
builder = builder.sslSocketFactory(sslSocketFactory);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
});
return builder.build();
}
gradle中的配置没有改,调用方式也不用改,至此,完美解决。