微信号: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 InputStream loadData(Priority priority) throws Exception {        Request.Builder requestBuilder = new Request.Builder()                .url(url.toStringUrl());        

        for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {            String key = headerEntry.getKey();            requestBuilder.addHeader(key, headerEntry.getValue());        }        Request request = requestBuilder.build();        Response response = client.newCall(request).execute();        responseBody = response.body();        

        if (!response.isSuccessful()) {            

            throw new IOException("Request failed with code: " + response.code());        }        

        long contentLength = responseBody.contentLength();        stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);        return stream;    }    @Override    

    public void cleanup() {        

        if (stream != null) {            

            try {                stream.close();            } catch (IOException e) {                

                // Ignored            }        }        

        if (responseBody != null) {            

            try {                responseBody.close();            } catch (IOException e) {                

                // Ignored.            }        }    }    @Override    public String getId() {        

        return url.getCacheKey();    }    @Override    public void cancel() {        

        // TODO: call cancel on the client when this method is called on a background thread. See #257    } }

OkHttpStreamFetcher类

public class OkHttpUrlLoader implements ModelLoader<GlideUrl, InputStream> {    /**     * The default factory for {@link OkHttpUrlLoader}s.     */    public static class Factory implements ModelLoaderFactory<GlideUrl, InputStream> {        private static volatile OkHttpClient internalClient;        

        private OkHttpClient client;        

        private static OkHttpClient getInternalClient() {            

            if (internalClient == null) {                synchronized (Factory.class) {                    

                    if (internalClient == null) {                        internalClient = new OkHttpClient();                    }                }            }            

            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<GlideUrl, InputStream> 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<InputStream> getResourceFetcher(GlideUrl model, int width, int height) {        

        return new OkHttpStreamFetcher(client, model);    } }


    第三步:Android.Manifest配置文件

    <meta-data            android:name="***.OkHttpGlideModule"              android:value="GlideModule" />

    by:***.OkHttpGlideModule中的”***“代表你文件路径


    



    很多人告诉我混淆的时候报错

    记得要加上

        -keep class cn.manmanda.util.https_glide.OkHttpGlideModule




        关于那三个文件已经打包丢到百度云了:

                回复”Glide加载Https文件“获得下载地址

 
Android每日干货 更多文章 详解7.0带来的新工具类:DiffUtil(上) 【Android】强大的SpannableStringBuilder 【安卓开发代码保护】浅谈代码混淆加固技术 Android复习之旅--Activity\/Service\/Fragment 生命周期 简单实用的Android ORM框架TigerDB
猜您喜欢 轻松一下:几则有趣的招聘 又拍云布局场景化 CDN,提升广电行业加速体验 8步变身数据科学家 来自架构师的能力模型-测试架构师 程序员如何爱护自己的身体?