美文网首页鱼乐DevSupport
Android之使用Glide加载 https 的图片

Android之使用Glide加载 https 的图片

作者: 不会吃鱼的小猫 | 来源:发表于2017-08-14 16:15 被阅读108次

    1.创建忽略证书的okhttphttpclient

    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() {
                                X509Certificate[] x509Certificates = new X509Certificate[0];
                                return x509Certificates;
                            }
                        }
                };
    
                // 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().newBuilder()
                        .sslSocketFactory(sslSocketFactory)
                        .protocols(Arrays.asList(Protocol.HTTP_1_1))
                        .hostnameVerifier(new HostnameVerifier() {
                            @Override
                            public boolean verify(String hostname, SSLSession session) {
                                return true;
                            }
                        }).build();
    
                return okHttpClient;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    

    2.调用该.register()方法来交换Glide的一些基本组成部分

    public class UnsafeOkHttpGlideModule implements GlideModule {
            @Override
            public void applyOptions(Context context, GlideBuilder builder) {
    
            }
    
            @Override
            public void registerComponents(Context context, Glide glide) {
                glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory());
            }
        }
    

    3.创建一个OkHttpUrlLoader,它使用该URL提供URL和输入流之间的链接UnsafeOkHttpClient。

    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 = 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<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);
        }
    }
    

    4.需要使用我们不安全的OkHttpClient将URL链接到活动的输入流。因此,我们需要另一个类来获取URL的响应输入流:

    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) {
                responseBody.close();
            }
        }
    
        @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
        }
    }
    

    5.配置glide加载https所需要的GlideModule

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

    相关文章

      网友评论

        本文标题:Android之使用Glide加载 https 的图片

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