美文网首页
glide4.0 支持https

glide4.0 支持https

作者: cain07 | 来源:发表于2017-09-12 20:02 被阅读0次

    1.自定义OkHttpGlideModule 官网上 让写注释 @GlideModule但是我加上后 没有用啊

    public class OkHttpGlideModule implements GlideModule {
        @Override
        public void applyOptions(Context context, GlideBuilder glideBuilder) {
        }
        @Override
        public void registerComponents(Context context, Glide glide, Registry registry) {
            registry.replace(GlideUrl.class,InputStream.class,new OkHttpUrlLoader.Factory());
        }
    }
    

    2. 自定义ModelLoader:

    一个简单的加载器,用于使用OkHttp通过http/https获取的流。

    public class OkHttpUrlLoader implements ModelLoader<GlideUrl,InputStream> {
    
    
        @Override
        public boolean handles(GlideUrl glideUrl) {
            return true;
        }
    
    
        /**
         * The default factory for {@link OkHttpUrlLoader}s.
         */
        public static class Factory implements ModelLoaderFactory<GlideUrl, InputStream> {
    
    
            private static volatile OkHttpClient internalClient;
            private                 OkHttpClient client;
    
    
            /**
             *
             * @return s
             */
            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());
            }
    
            /**
             *
             * @param client s
             */
            public Factory(OkHttpClient client) {
                this.client = client;
            }
    
            @Override
            public ModelLoader<GlideUrl, InputStream> build(MultiModelLoaderFactory multiModelLoaderFactory) {
                return new OkHttpUrlLoader(client);
            }
    
            @Override
            public void teardown() {
    
            }
        }
    
        private final OkHttpClient client;
    
        /**
         *
         * @param client s
         */
        public OkHttpUrlLoader(OkHttpClient client) {
            this.client = client;
        }
    
        @Nullable
        @Override
        public LoadData<InputStream> buildLoadData(GlideUrl glideUrl, int i, int i1, Options options) {
    
            return new LoadData<InputStream>(glideUrl,new OkHttpStreamFetcher(client,glideUrl));
        }
    
    }
    

    3自定义DataFetcher重写DataFetcher,获取OkHttp库的数据流。

    public class OkHttpStreamFetcher implements DataFetcher<InputStream> {
    
    
        private final OkHttpClient client;
        private final GlideUrl url;
        private InputStream stream;
        private ResponseBody responseBody;
    
        /**
         * @param client s
         * @param url    s
         */
        public OkHttpStreamFetcher(OkHttpClient client, GlideUrl url) {
            this.client = client;
            this.url = url;
        }
    
        @Override
        public void loadData(Priority priority, final DataCallback<? super InputStream> dataCallback) {
            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();
    
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    dataCallback.onLoadFailed(e);
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    responseBody = response.body();
                    if (response.isSuccessful()) {
                        long contentLength = responseBody.contentLength();
                        stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
                        dataCallback.onDataReady(stream);
                    } else {
                        dataCallback.onLoadFailed(new HttpException(response.message(), response.code()));
                    }
                }
            });
    
        }
    
        @Override
        public void cleanup() {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    // Ignored
                    e.printStackTrace();
                }
            }
            if (responseBody != null) {
                responseBody.close();
            }
        }
    
        @Override
        public void cancel() {
        }
    
        @Override
        public Class<InputStream> getDataClass() {
            return InputStream.class;
        }
    
        @Override
        public DataSource getDataSource() {
            return DataSource.REMOTE;
        }
    }
    

    4.由于公司是https的,我就直接信任所有的证书了, 在getInstance中就是一个单利模式,然后封装了一个handler用于主线程更新使用

    public class UnsafeOkHttpClient {
    
        /**
         *
         * @return s
         */
        public static OkHttpClient getUnsafeOkHttpClient() {
            OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
    
            //https
            try {
    
                SSLContext sslContext = SSLContext.getInstance("TLS");
                X509TrustManager trustManager = new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    
                    }
    
                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    
                    }
    
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
    
                };
    
                sslContext.init(null, new TrustManager[]{trustManager}, new SecureRandom());
                httpClientBuilder.sslSocketFactory(sslContext.getSocketFactory());
    
            } catch (NoSuchAlgorithmException e) {
                Log.i(TAG, e.getMessage());
            } catch (KeyManagementException e) {
                Log.i(TAG, e.getMessage());
            }
    
    
            httpClientBuilder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            OkHttpClient client = httpClientBuilder.build();
    
            return client;
        }
    }
    

    5.Finally, you need to declare the new module in the AndroidManifest.xml:

    <application>
            <meta-data    android:name="io.futurestud.tutorials.glide.glidemodule.OkHttpGlideModule"
                android:value="GlideModule" />
            ...
        </application>
    

    参考相关文献

    http://bumptech.github.io/glide/doc/migrating.html
    https://futurestud.io/tutorials/glide-module-example-accepting-self-signed-https-certificates

    相关文章

      网友评论

          本文标题:glide4.0 支持https

          本文链接:https://www.haomeiwen.com/subject/bvkhsxtx.html