微信号:ardays

介绍:android每日绝对干货

Glide加载https图片

2017-01-03 18:04 Android每日干货

因为在WWDC 2016开发者大会上,苹果宣布了一个最后期限:到2017年1月1日 App Store中的所有应用都必须启用App Transport Security安全功能,所以受之牵连,因此图片加载框架也要兼容https接口.


        废话不多说,下面看步骤吧


        第一步:在项目app/build.gradle文件下添加依赖:

      compile 'com.github.bumptech.glide:glide:3.6.1' 

       compile 'com.squareup.okhttp:okhttp:2.7.2'


       第二步:在项目底下添加创建一个文件把下面这代码拷贝进去

OkHttpGlideModule类:改写成如下忽略证书,支持https

public class OkHttpGlideModule implements GlideModule {    @Override    public void applyOptions(Context context, GlideBuilder builder) {        // Do nothing.    }    @Override    public void registerComponents(Context context, Glide glide) {        OkHttpClient okHttpClient=new OkHttpClient();        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.setSslSocketFactory(sslContext.getSocketFactory());        okHttpClient.setHostnameVerifier(DO_NOT_VERIFY);        glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okHttpClient));    } }

OkHttpStreamFetcher类

public class OkHttpStreamFetcher implements DataFetcher<InputStream> {    private final OkHttpClient client;    

    private final GlideUrl url;    

    private InputStream stream;    

    private ResponseBody responseBody;    

    public OkHttpStreamFetcher(OkHttpClient client, GlideUrl url) {        

        this.client = client;        

        this.url = url;    }    @Override    

    public