Glide支持https图片地址的加载

2017-06-15  本文已影响0人  sk强仔

Glide图片加载不了,加载https图片解决

Glide加载网络图片,有些图片显示不出来。很大一部分的原因是https的不兼容。以下是我从CSDN上查找的这个问题的解决,分享给大家。

1、在build.gradle中添加依赖:                                                                                                                     compile'com.github.bumptech.glide:glide:3.6.1'                                                                                                   compile'com.squareup.okhttp:okhttp:2.7.2'                                                                                                             compile'com.github.bumptech.glide:okhttp-integration:1.4.0@aar'

2.拷贝'com.github.bumptech.glide:okhttp-integration:1.4.0@aar'里面3个类OkHttpGlideModule ,OkHttpUrlLoader,OkHttpStreamFetcher的源码;OkHttpGlideModule类:改写成如下忽略证书,支持https.

public class OkHttpGlideModule implements GlideModule {

@Override

public void applyOptions(Context context, GlideBuilder builder) {

// Do nothing.

}

@Override

public void registerComponents(Context context, Glide glide) {

OkHttpClient okHttpClient=new OkHttpClient();

X509TrustManager xtm = new X509TrustManager() {

@Override

public void checkClientTrusted(X509Certificate[] chain, String authType) {

}

@Override

public void checkServerTrusted(X509Certificate[] chain, String authType) {

}

@Override

public X509Certificate[] getAcceptedIssuers() {

X509Certificate[] x509Certificates = new X509Certificate[0];

return x509Certificates;

}

};

SSLContext sslContext = null;

try {

sslContext = SSLContext.getInstance("SSL");

sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (KeyManagementException e) {

e.printStackTrace();

}

HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {

@Override

public boolean verify(String hostname, SSLSession session) {

return true;

}

};

okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());

okHttpClient.setHostnameVerifier(DO_NOT_VERIFY);

glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okHttpClient));

}}

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.EntryheaderEntry : 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) {

try {

responseBody.close();

} catch (IOException e) {

// Ignored.}}}

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

public class OkHttpUrlLoader implements ModelLoader{    /**    * The default factory for {@link OkHttpUrlLoader}s.    */    public static class Factory implements ModelLoaderFactory{        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 ModelLoaderbuild(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 DataFetchergetResourceFetcher(GlideUrl model, int width, int height) {

return new OkHttpStreamFetcher(client, model);}}

3、删除在build.gradle中依赖:
compile'com.github.bumptech.glide:okhttp-integration:1.4.0@aar';

4、在Android.Manifest中配置:

<meta-da

android:name="***.OkHttpGlideModule"

android:value="GlideModule"/>

此时,重新运行后发现可以加载https啦。

但是,在发布后会出现找不到OkHttpGlideModule类。是因为被混淆了,因此发布时还得注意下

上一篇下一篇

猜你喜欢

热点阅读