Glide加载自签名认证的https图片

困扰了很多天的问题,网上也找了很多技术帖看,但很多都是零零散散,下面我就把我解决过程中遇到的问题点跟大家说一下。

一、添加依赖:

  • compile ‘com.github.bumptech.glide:glide:3.7.0’
  • compile ‘com.squareup.okhttp:okhttp:2.7.5’ //添加okhttp3会出现问题具体下面会说

二、重写需要的类:

1、

public class OkHttpGlideModule implements GlideModule {
@Override
public void applyOptions(Context context, GlideBuilder builder) {
    // Do nothing.
}

@Override
public void registerComponents(Context context, Glide glide) {
    glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory());
}

2、

public class OkHttpUrlLoader implements ModelLoader {

/**
 * The default factory for {@link OkHttpUrlLoader}s.
 */
public static class Factory implements ModelLoaderFactory {
    private static volatile OkHttpClient internalClient;
    private                 OkHttpClient client;

    private static OkHttpClient getInternalClient() {
        if (internalClient == null) {
            synchronized (Factory.class) {
                if (internalClient == null) {
                    internalClient = UnsafeOkHttpClient.getUnsafeOkHttpClient();
                }
            }
        }
        return internalClient;
    }

    /**
     * Constructor for a new Factory that runs requests using a static singleton client.
     */
    public Factory() {
        this(getInternalClient());
    }

    /**
     * Constructor for a new Factory that runs requests using given client.
     */
    public Factory(OkHttpClient client) {
        this.client = client;
    }

    @Override
    public ModelLoader build(Context context, GenericLoaderFactory factories) {
        return new OkHttpUrlLoader(client);
    }

    @Override
    public void teardown() {
        // Do nothing, this instance doesn't own the client.
    }
}

private final OkHttpClient client;

public OkHttpUrlLoader(OkHttpClient client) {
    this.client = client;
}

@Override
public DataFetcher getResourceFetcher(GlideUrl model, int width, int height) {
    return new OkHttpStreamFetcher(client, model);
}

3、

public class OkHttpUrlLoader implements ModelLoader {

/**
 * The default factory for {@link OkHttpUrlLoader}s.
 */
public static class Factory implements ModelLoaderFactory {
    private static volatile OkHttpClient internalClient;
    private                 OkHttpClient client;

    private static OkHttpClient getInternalClient() {
        if (internalClient == null) {
            synchronized (Factory.class) {
                if (internalClient == null) {
                    internalClient = UnsafeOkHttpClient.getUnsafeOkHttpClient();
                }
            }
        }
        return internalClient;
    }

    /**
     * Constructor for a new Factory that runs requests using a static singleton client.
     */
    public Factory() {
        this(getInternalClient());
    }

    /**
     * Constructor for a new Factory that runs requests using given client.
     */
    public Factory(OkHttpClient client) {
        this.client = client;
    }

    @Override
    public ModelLoader build(Context context, GenericLoaderFactory factories) {
        return new OkHttpUrlLoader(client);
    }

    @Override
    public void teardown() {
        // Do nothing, this instance doesn't own the client.
    }
}

private final OkHttpClient client;

public OkHttpUrlLoader(OkHttpClient client) {
    this.client = client;
}

@Override
public DataFetcher getResourceFetcher(GlideUrl model, int width, int height) {
    return new OkHttpStreamFetcher(client, model);
}
  • 这个类重要的代码是创建 internalClient 对象:internalClient = UnsafeOkHttpClient.getUnsafeOkHttpClient();。

4、

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 null;
                    }
                }
        };

        // 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);
    }
}
  • 如果使用的okhttp3,调用okHttpClient.setSslSocketFactory(sslSocketFactory);这几个方法会报错
  • 创建 OkHttpClient 禁用掉所有的 SSL 证书检查。

三、在AndroidManifest中配置

  • Glide需要加载网络图片所以需要网络图片
  • 配置我们刚刚写的OkHttpGlideModule
  • meta-data
    android:name=”com.lee.glidetest.https.OkHttpGlideModule”
    android:value=”GlideModule”/>

四、现在你就使用Glide加载自签名的https图片啦

public void getHttpsImg(View view) {
    String url = "https://travel.12306.cn/imgs/resources/uploadfiles/images/a9b9c76d-36ba-4e4a-8e02-9e6a1a991da0_news_W540_H300.jpg";
    Glide.with(this)
            .load(url)
            .asBitmap()
            .listener(new RequestListener() {
                @Override
                public boolean onException(Exception e, String model, Target target, boolean isFirstResource) {
                    System.out.println("--------------Exception--------------" + e);
                    return false;
                }

                @Override
                public boolean onResourceReady(Bitmap resource, String model, Target target, boolean isFromMemoryCache, boolean isFirstResource) {
                    return false;
                }
            })
            .into(imageView);
}

你可能感兴趣的:(android)