App module build.gradle中:
plugins {
id 'kotlin-kapt'
}
dependencies {
api "com.github.bumptech.glide:glide:$GLIDE_VERSION"
api "com.github.bumptech.glide:okhttpintegration:$GLIDE_VERSION"
kapt "com.github.bumptech.glide:compiler:$GLIDE_VERSION"
}
新建 UnsafeOkHttpClient 类:
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
public class UnsafeOkHttpClient {
public static OkHttpClient getUnsafeOkHttpClient() {
try {
final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType){
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType){
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
// 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.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);
builder.hostnameVerifier((hostname, session) -> true);
return builder.build();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
新建 MyAppGlideModule 类:
import android.content.Context
import com.bumptech.glide.Glide
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import java.io.InputStream
@GlideModule
class MyAppGlideModule: AppGlideModule() {
override fun isManifestParsingEnabled(): Boolean {
return false
}
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
super.registerComponents(context, glide, registry)
val client = UnsafeOkHttpClient.getUnsafeOkHttpClient()
registry.replace(
GlideUrl::class.java, InputStream::class.java,
OkHttpUrlLoader.Factory(client)
)
}
}
然后rebuild项目,生成文件,在使用glide前调用一次:
GlideApp.init(applicationContext, GlideBuilder())
|