在使用Glide的过程中踩了不少坑,相信很多人也遇到过,首先Glide默认使用的是HttpUrlConnection来下载图片,一般场景足够了,高级点的,直接换用okhttp,Glide官网也有相关教程,再高级点,Glide+OkHttp+Https(私有证书),方案网上也有,自定义GlideModule即可
@GlideModule
public class OkHttpGlideModule extends AppGlideModule {
@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
OkHttpClient client = UnsafeOkHttpClient.getUnsafeOkHttpClient();
registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(client));
}
}
这个UnsafeOkHttpClient.java
的定义用过Okhttp的我觉得都知道怎么写,无非就是忽略对https证书的校验
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) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@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;
}
});
OkHttpClient okHttpClient = builder.build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
到目前为止,已经可以用Glide来加载采用Https传输的图片了,并且忽略了证书校验,更高级点的来了,如果想要加载的url是下面这种形式呢:
https://[ipv6]:3000/demo.png
不再是域名了,改为ipv6了,如果还是按上面的方案,会出现如下的问题:
09-02 08:21:19.494 30626-30626/W/Glide: Load failed for https://[fbb9:62a0:fad4:bb4a:966:11e1:e147:a8b3]:3000/static/fb4c5e3e67dac4100ea88905827ea96c//Download/MiXun/CloudFile/2b8f54a68b338e34f595f1fba0472d91.png with size [179x179]
class com.bumptech.glide.load.engine.GlideException: Failed to load resource
There was 1 cause:
java.lang.IllegalArgumentException(Invalid URL port: "62a0:fad4:bb4a:966:11e1:e147:a8b3%5D:3000")
call GlideException#logRootCauses(String) for more detail
Cause (1 of 1): class java.lang.IllegalArgumentException: Invalid URL port: "62a0:fad4:bb4a:966:11e1:e147:a8b3%5D:3000"
很明显,Glide把url中的[]
给编码了,导致okhttp识别url错误,可以查看 GlideUrl.java 的源码中有这样一句:
private static final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%;$";
这里面恰恰没有[]
在getSafeStringUrl
方法中会根据这个ALLOWED_URI_CHARS
来决定哪些字符不需要被转码
private String getSafeStringUrl() {
if (TextUtils.isEmpty(safeStringUrl)) {
String unsafeStringUrl = stringUrl;
if (TextUtils.isEmpty(unsafeStringUrl)) {
unsafeStringUrl = Preconditions.checkNotNull(url).toString();
}
safeStringUrl = Uri.encode(unsafeStringUrl, ALLOWED_URI_CHARS);
}
return safeStringUrl;
}
也就是说只要ALLOWED_URI_CHARS
中包含了[]
就可以了,但是Glide的源码不是说改就能改的
下面说一下我自己比较苟且的做法
// OkHttpGlideModule.java
@GlideModule
public class OkHttpGlideModule extends AppGlideModule {
@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
// 自定义OkHttpClient
OkHttpClient client = UnsafeOkHttpClient.getUnsafeOkHttpClient();
// 采用自定义的CustomOkHttpUrlLoader
registry.replace(GlideUrl.class, InputStream.class, new CustomOkHttpUrlLoader.Factory(client));
}
}
// CustomOkHttpUrlLoader.java
// 按照Glide提供的OkHttpUrlLoader.java复制过来的,把里面的OkHttpUrlLoader全部替换为CustomOkHttpUrlLoader
public class CustomOkHttpUrlLoader implements ModelLoader<GlideUrl, InputStream> {
private final Call.Factory client;
// Public API.
@SuppressWarnings("WeakerAccess")
public CustomOkHttpUrlLoader(@NonNull Call.Factory client) {
this.client = client;
}
@Override
public boolean handles(@NonNull GlideUrl url) {
return true;
}
@Override
public LoadData<InputStream> buildLoadData(@NonNull GlideUrl model, int width, int height,
@NonNull Options options) {
// 注意这里,不再是原来的OkHttpStreamFetcher,而是改为自定义的CustomOkHttpStreamFetcher
return new LoadData<>(model, new CustomOkHttpStreamFetcher(client, model));
}
/**
* The default factory for {@link com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader}s.
*/
// Public API.
@SuppressWarnings("WeakerAccess")
public static class Factory implements ModelLoaderFactory<GlideUrl, InputStream> {
private static volatile Call.Factory internalClient;
private final Call.Factory client;
private static Call.Factory getInternalClient() {
if (internalClient == null) {
synchronized (CustomOkHttpUrlLoader.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.
*
* @param client this is typically an instance of {@code OkHttpClient}.
*/
public Factory(@NonNull Call.Factory client) {
this.client = client;
}
@NonNull
@Override
public ModelLoader<GlideUrl, InputStream> build(MultiModelLoaderFactory multiFactory) {
return new CustomOkHttpUrlLoader(client);
}
@Override
public void teardown() {
// Do nothing, this instance doesn't own the client.
}
}
}
// CustomOkHttpStreamFetcher.java
// 这个类也是复制的OkHttpStreamFetcher.java,需要注意的是改动了一个地方
public class CustomOkHttpStreamFetcher implements DataFetcher<InputStream>, okhttp3.Callback {
private static final String TAG = "OkHttpFetcher";
private final Call.Factory client;
private final GlideUrl url;
private InputStream stream;
private ResponseBody responseBody;
private DataCallback<? super InputStream> callback;
// call may be accessed on the main thread while the object is in use on other threads. All other
// accesses to variables may occur on different threads, but only one at a time.
private volatile Call call;
// Public API.
@SuppressWarnings("WeakerAccess")
public CustomOkHttpStreamFetcher(Call.Factory client, GlideUrl url) {
this.client = client;
this.url = url;
}
@Override
public void loadData(@NonNull Priority priority,
@NonNull final DataCallback<? super InputStream> callback) {
// 不再是url.toStringUrl(),而是改为了 url.getCacheKey()
// 这样Glide不会将url进行转义了,或者说自己对url进行转义,不再采用GlideUrl中提供的方法
Request.Builder requestBuilder = new Request.Builder().url(url.getCacheKey());
for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
String key = headerEntry.getKey();
requestBuilder.addHeader(key, headerEntry.getValue());
}
Request request = requestBuilder.build();
this.callback = callback;
call = client.newCall(request);
call.enqueue(this);
}
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "OkHttp failed to obtain result", e);
}
callback.onLoadFailed(e);
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) {
responseBody = response.body();
if (response.isSuccessful()) {
long contentLength = Preconditions.checkNotNull(responseBody).contentLength();
stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
callback.onDataReady(stream);
} else {
callback.onLoadFailed(new HttpException(response.message(), response.code()));
}
}
@Override
public void cleanup() {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
// Ignored
}
if (responseBody != null) {
responseBody.close();
}
callback = null;
}
@Override
public void cancel() {
Call local = call;
if (local != null) {
local.cancel();
}
}
@NonNull
@Override
public Class<InputStream> getDataClass() {
return InputStream.class;
}
@NonNull
@Override
public DataSource getDataSource() {
return DataSource.REMOTE;
}
}
上述方案采用苟且的方式绕过了GlideUrl.java中的编码,不用担心url编码的问题,因为okhttp会给你再次编码的
这样,无论是域名,ipv4还是ipv6,采用http还是https,都可以愉快的撸起来了