Glide 3.7.0 加载https 图片的解决办法

需要的依赖如下

    compile 'com.squareup.okhttp3:okhttp:3.3.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'

需要以下三个类

OkHttpStreamFetcher

package com.trs.nxnews.common.util.glide;

import com.bumptech.glide.Priority;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.util.ContentLengthInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;


/**
 * Fetches an {@link InputStream} using the okhttp library.
 */
public class OkHttpStreamFetcher implements DataFetcher {
    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 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
    }
}

OkHttpUrlLoader

package com.trs.nxnews.common.util.glide;
import android.content.Context;


import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.GenericLoaderFactory;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;

import java.io.InputStream;

import okhttp3.OkHttpClient;

/**
 * author           Alpha58
 * time             2017/1/5 22:57
 * desc             ${TODO}
 * 

* upDateAuthor $Author$ * upDate $Date$ * upDateDesc ${TODO} */ 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 = new OkHttpClient(); } } } 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 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 getResourceFetcher(GlideUrl model, int width, int height) { return new OkHttpStreamFetcher(client, model); } }

UnsafeOkHttpClient

package com.trs.nxnews.common.util.glide;

import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;


/**
 * Created by zhuguohui on 2018/7/11.
 */

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

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // 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.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            builder.connectTimeout(20, TimeUnit.SECONDS);
            builder.readTimeout(20, TimeUnit.SECONDS);

            OkHttpClient okHttpClient = builder.build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

注册

package com.trs.nxnews.common.util.glide;

import android.content.Context;


import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.module.GlideModule;

import java.io.InputStream;

/**
 * A {@link GlideModule} implementation to replace Glide's default
 * {@link java.net.HttpURLConnection} based {@link com.bumptech.glide.load.model.ModelLoader} with an OkHttp based
 * {@link com.bumptech.glide.load.model.ModelLoader}.
 *
 * 

* If you're using gradle, you can include this module simply by depending on the aar, the module will be merged * in by manifest merger. For other build systems or for more more information, see * {@link GlideModule}. *

*/
public class OkHttpGlideModule implements GlideModule { @Override public void applyOptions(Context context, GlideBuilder builder) { // Do nothing. } @Override public void registerComponents(Context context, Glide glide) { glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(UnsafeOkHttpClient.getUnsafeOkHttpClient())); } }

在AndroidManiFests中配置

    
        <meta-data
            android:name="com.trs.nxnews.common.util.glide.OkHttpGlideModule"
            android:value="GlideModule"/>

你可能感兴趣的:(Android)