美文网首页安卓开发Android 文章
安卓glide加载https图片

安卓glide加载https图片

作者: 夜封雪 | 来源:发表于2018-01-18 15:43 被阅读50次

说明:glide加载https图片失败,是因为glide默认http请求。如果想让它自动加载https图片,只需要自定义一个GlideModule,把请求换成带https请求的就可以了

第一步、定义一个带https的请求

public class OkHttpsClient {
    public static OkHttpClient OkHttpsClient() {
        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() {
                            return null;
                        }
                    }
            };

            // 这里呢是获取证书(单向或者双向认证)
            SSLContext sslContext = Xutils.getSSLContext(BestnetApplication.contextApplication);
            if (sslContext == null) {
                sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            }
            // Create an ssl socket factory with our all-trusting manager
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            // 这个用到了Okhttp3.*
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .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);
        }
    }
}

第二步:定义ModelLoader和ModelLoader.Factory

public class OkHttpsUrlLoader implements ModelLoader<GlideUrl, InputStream> {

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

        private static okhttp3.OkHttpClient getInternalClient() {
            if (internalClient == null) {
                synchronized (Factory.class) {
                    if (internalClient == null) {
                        internalClient = OkHttpsClient.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(okhttp3.OkHttpClient client) {
            this.client = client;
        }

        @Override
        public ModelLoader<GlideUrl, InputStream> build(Context context, GenericLoaderFactory factories) {
            return new OkHttpsUrlLoader(client);
        }

        @Override
        public void teardown() {
            // Do nothing, this instance doesn't own the client.
        }
    }

    private final okhttp3.OkHttpClient client;

    public OkHttpsUrlLoader(okhttp3.OkHttpClient client) {
        this.client = client;
    }
    @Override
    public DataFetcher<InputStream> getResourceFetcher(GlideUrl model, int width, int height) {
        return new OkHttpsStreamFetcher(client, model);
    }
}

第三步、ModelLoader的getResourceFetcher返回一个DataFetcher,我们给它传入一个OkHttpClient实例,让它通过OkHttpClient发起请求

public class OkHttpsStreamFetcher implements DataFetcher<InputStream> {
    private final OkHttpClient client;
    private final GlideUrl url;
    private InputStream stream;
    private ResponseBody responseBody;

    public OkHttpsStreamFetcher(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) {
                e.printStackTrace();
            }
        }
        if (responseBody != null) {
            try {
                responseBody.close();
            } catch (Exception e) {
               e.printStackTrace();
            }
        }
    }

    @Override
    public String getId() {
        return url.getCacheKey();
    }

    @Override
    public void cancel() {

    }
}

第四步、自定义一个GlideModule,在OkHttpsGlideModule中进行关联

public class OkHttpsGlideModule 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 OkHttpsUrlLoader.Factory());
    }
}

第五步、在AndroidManifest.xml中的<application>标签下定义<meta-data>,这样Glide才能知道我们定义了这么一个类,其中android:name是我们自定义的GlideModule的完整路径,而android:value就固定写死GlideModule。注册后glide就可以自动加载https图片了。

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.example.mian.OkHttpsGlideModule"
            android:value="GlideModule"/>
    </application>

引用的架包:

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

相关文章

网友评论

    本文标题:安卓glide加载https图片

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