安卓glide加載https圖片

說(shuō)明:glide加載https圖片失敗,是因?yàn)間lide默認(rèn)http請(qǐng)求。如果想讓它自動(dòng)加載https圖片,只需要自定義一個(gè)GlideModule,把請(qǐng)求換成帶https請(qǐng)求的就可以了

第一步、定義一個(gè)帶https的請(qǐng)求

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

            // 這里呢是獲取證書(單向或者雙向認(rèn)證)
            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();

            // 這個(gè)用到了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返回一個(gè)DataFetcher,我們給它傳入一個(gè)OkHttpClient實(shí)例,讓它通過(guò)OkHttpClient發(fā)起請(qǐng)求

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() {

    }
}

第四步、自定義一個(gè)GlideModule,在OkHttpsGlideModule中進(jìn)行關(guān)聯(lián)

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>標(biāo)簽下定義<meta-data>,這樣Glide才能知道我們定義了這么一個(gè)類,其中android:name是我們自定義的GlideModule的完整路徑,而android:value就固定寫死GlideModule。注冊(cè)后glide就可以自動(dòng)加載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'
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容