說明: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發(fā)起請求
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中進行關(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才能知道我們定義了這么一個類产还,其中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'