Glide+OkHttp訪問IPv6出錯的解決方案

weixin_33670713發表於2018-09-03

在使用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,都可以愉快的擼起來了

相關文章