android ipv6http请求失败,Glide+OkHttp访问IPv6出错的解决方案

在使用Glide的过程中踩了不少坑,相信很多人也遇到过,首先Glide默认使用的是HttpUrlConnection来下载图片,一般场景足够了,高级点的,直接换用okhttp,Glide官网也有相关教程,再高级点,Glide+OkHttp+Https(私有证书),方案网上也有,自定义GlideModule即可

@GlideModule

public class OkHttpGlideModule extends AppGlideModule {

@Override

public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {

OkHttpClient client = UnsafeOkHttpClient.getUnsafeOkHttpClient();

registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(client));

}

}

这个UnsafeOkHttpClient.java的定义用过Okhttp的我觉得都知道怎么写,无非就是忽略对https证书的校验

public class UnsafeOkHttpClient {

public static OkHttpClient getUnsafeOkHttpClient() {

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() {

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]);

<

你可能感兴趣的:(android,ipv6http请求失败)