美文网首页
Android Glide加载Https图片

Android Glide加载Https图片

作者: itfitness | 来源:发表于2020-04-27 17:14 被阅读0次

    目录

    目录

    问题描述

    Android某些版本的手机不能够加载Https图片

    解决方法

    1. 使用Glide图片加载框架
    2. 创建如下4个类


    OkHttpStreamFetcher.java
    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) {
                }
            }
            if (responseBody != null) {
                responseBody.close();
            }
        }
    
        @Override
        public String getId() {
            return url.getCacheKey();
        }
    
        @Override
        public void cancel() {
        }
    
    }
    

    OkHttpUrlLoader.java

    public class OkHttpUrlLoader implements ModelLoader<GlideUrl, InputStream> {
    
        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;
            }
    
            public Factory() {
                this(getInternalClient());
            }
    
            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() {
            }
        }
    
        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);
        }
    }
    

    SSLSocketClient.java

    public class SSLSocketClient {
        //获取这个SSLSocketFactory
        public static SSLSocketFactory getSSLSocketFactory() {
            try {
                SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, getTrustManager(), new SecureRandom());
                return sslContext.getSocketFactory();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
        //获取TrustManager
        private static TrustManager[] getTrustManager() {
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {
                        }
    
                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {
                        }
    
                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[]{};
                        }
                    }
            };
            return trustAllCerts;
        }
    
        //获取HostnameVerifier
        public static HostnameVerifier getHostnameVerifier() {
            HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            };
            return hostnameVerifier;
        }
    }
    

    GlideConfiguration.java

    public class GlideConfiguration implements GlideModule {
        @Override
        public void applyOptions(Context context, GlideBuilder glideBuilder) {
            glideBuilder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);
        }
    
        @Override
        public void registerComponents(Context context, Glide glide) {
            OkHttpClient build = new OkHttpClient().newBuilder()
                    .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
                    .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                    .build();
            glide.register(GlideUrl.class, InputStream.class,new OkHttpUrlLoader.Factory(build));
        }
    }
    

    3. AndroidManifest配置

    <meta-data
                android:name="com.common.sys.GlideConfiguration"//这里填自己类的路径
                android:value="GlideModule" /> 
    

    参考文章

    https://blog.csdn.net/u014752325/article/details/73217577

    相关文章

      网友评论

          本文标题:Android Glide加载Https图片

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