最近在项目中遇到加载https图片,单纯的glide遇到了加载不出来的问题,下面讲一下解决过程,以便可以帮助到大家 (0.0)
- 注入依赖
compile "com.github.bumptech.glide:okhttp3-integration:4.0.0-RC1"
-
拷贝相关类到自己的工程目录下
修改相关代码
- OkHttpGlideModule
public class OkHttpGlideModule implements GlideModule {
@Override
public void applyOptions(Context context, GlideBuilder builder) {
// Do nothing.
}
@Override
public void registerComponents(Context context, Glide glide, Registry registry) {
X509TrustManager xtm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] x509Certificates = new X509Certificate[0];
return x509Certificates;
}
};
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslContext.getSocketFactory());
builder.hostnameVerifier(DO_NOT_VERIFY);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
builder.connectTimeout(20, TimeUnit.SECONDS);
builder.readTimeout(20,TimeUnit.SECONDS);
registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(builder.build()));
}
}
- OkHttpLibraryGlideModule
@GlideModule
public final class OkHttpLibraryGlideModule extends LibraryGlideModule {
@Override
public void registerComponents(Context context, Glide glide, Registry registry) {
registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory());
}
}
- 配置AndroidManifest.xml
<meta-data
android:name="com.***.***.OkHttpGlideModule"
android:value="GlideModule"/>
- 移除依赖
// compile "com.github.bumptech.glide:okhttp3-integration:4.0.0-RC1"
到这一步你就可以成功加载https 的图片了
参考文章
Glide加载https图片
Glide4.0加载https图片
有不同方法欢迎留言
每星期至少一篇跟新,感兴趣可以关注。
一起学习,一起进步。