Glide+OkHttp訪問IPv6出錯的解決方案
在使用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,都可以愉快的擼起來了
相關文章
- 訪問 HTTPS 網站時的 SSL 錯誤解決方案HTTP網站
- GitHub 不能訪問解決方案Github
- hadoop訪問不到8088解決方案Hadoop
- Github訪問速度慢的解決方案Github
- 同時訪問內外網解決方案
- Xcode更新後Pod init出錯的解決方案XCode
- ubuntu 20.04 安裝 vim 出錯的解決方案Ubuntu
- npm install報錯、失敗,出現network proxy問題解決方案NPM
- 分享跨域訪問的解決方案與基礎分析跨域
- matplotlib中文報錯問題及解決方案
- 解決 github 訪問不了的問題Github
- 解決github訪問慢的問題Github
- 整合Health Kit時因證書問題出現錯誤碼50063的解決方案
- Ubuntu20.04出現段錯誤核心已轉儲問題解決方案Ubuntu
- photoshop匯出png發生未知錯誤的解決方案,ps匯出發生未知錯誤怎麼解決
- 真機除錯出現 application installation failed 錯誤 解決方案除錯APPAI
- 分散式系統設計中的併發訪問解決方案分散式
- 乾貨分享——連結被微信停止訪問的解決方案
- 解決JS跨域訪問的問題JS跨域
- BitComet位元彗星解決埠阻塞問題/黃燈問題,如何使用IPv6實現公網訪問
- 換IP經常出現的問題及其解決方案
- 寶塔皮膚 新增網站訪問不瞭解決方案網站
- 解決訪問Github與clone很慢的問題Github
- 解決訪問 GitHub 與 clone 很慢的問題Github
- localhost拒絕訪問的解決方法localhost
- 解決MySQL server has gone away錯誤的解決方案MySqlServerGo
- Django(21)migrate報錯的解決方案Django
- Intellij IDEA使用@Autowired註解,出現could not autowire錯誤,解決方案IntelliJIdea
- ElasticSearch實戰系列十一: ElasticSearch錯誤問題解決方案Elasticsearch
- 解決 Github 國內訪問問題Github
- ADFS4.0 使用nginx做反向代理訪問報502錯的解決方法Nginx
- wordress小程式圖片訪問出現404問題解決辦法
- minio報錯SignatureDoesNotMatch解決方案
- Linux下錯誤解決方案Linux
- latex 錯誤以及解決方案
- WordPress網站訪問慢解決方案(超詳細圖文教程)網站
- Angular應用解決跨域訪問的問題Angular跨域
- 安裝npm報錯,安裝淘寶映象cnpm時出現問題及解決方案NPM