android https 图片,安卓glide加载https图片

说明: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 {

/** * The default factory for {@link OkHttpsUrlLoader}s. */

public static class Factory implements ModelLoaderFactory {

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 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 getResourceFetcher(GlideUrl model, int width, int height) {

return new OkHttpsStreamFetcher(client, model);

}

}

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

public class OkHttpsStreamFetcher implements DataFetcher {

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 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中的标签下定义,这样Glide才能知道我们定义了这么一个类,其中android:name是我们自定义的GlideModule的完整路径,而android:value就固定写死GlideModule。注册后glide就可以自动加载https图片了。

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:supportsRtl="true"

android:theme="@style/AppTheme">

android:name="com.example.mian.OkHttpsGlideModule"

android:value="GlideModule"/>

引用的架包:

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值