Glide 加载Https 配置

  • 继承 GlideModule,在registerComponents注册组件中修改Glide 加载配置,这里我们使用的是使用Okhttp 去加载SSL 配置,实现Glide 加载HTTPS 的方案
    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
    
    
        // Do nothing.
    }

    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull     Registry registry) {
    
    
        OkHttpClient okhttpClient = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true) // 设置出现错误进行重新连接。
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory())
                .hostnameVerifier(new TrustAllCerts.TrustAllHostnameVerifier())
                .build();
        registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okhttpClient));
    }
  • OkHttpStreamFetcher
public class OkHttpStreamFetcher implements DataFetcher<InputStream> {
    
    
    private static final String TAG = "OkHttpFetcher";
    private final Call.Factory client;
    private final GlideUrl url;
    @Synthetic
    InputStream stream;
    @Synthetic
    ResponseBody responseBody;
    private volatile Call call;

    public OkHttpStreamFetcher(Call.Factory client, GlideUrl url) {
    
    
        this.client = client;
        this.url = url;
    }

    @Override
    public void loadData(Priority priority, final DataCallback<? super InputStream> callback) {
    
    
        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();

        call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
    
    
            @Override
            public void onFailure(Call call, IOException e) {
    
    
                if (Log.isLoggable(TAG, Log.DEBUG)) {
    
    
                    Log.d(TAG, "OkHttp failed to obtain result", e);
                }
                callback.onLoadFailed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
    
    
                responseBody = response.body();
                if (response.isSuccessful()) {
    
    
                    long contentLength = 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();
        }
    }

    @Override
    public void cancel() {
    
    
        Call local = call;
        if (local != null) {
    
    
            local.cancel();
        }
    }

    @Override
    public Class<InputStream> getDataClass() {
    
    
        return InputStream.class;
    }

    @Override
    public DataSource getDataSource() {
    
    
        return DataSource.REMOTE;
    }
}
  • OkHttpUrlLoader
public class OkHttpUrlLoader implements ModelLoader<GlideUrl, InputStream> {
    
    
    private final Call.Factory client;

    public OkHttpUrlLoader(Call.Factory client) {
    
    
        this.client = client;
    }

    @Override
    public boolean handles(GlideUrl url) {
    
    
        return true;
    }

    @Override
    public LoadData<InputStream> buildLoadData(GlideUrl model, int width, int height,
                                               Options options) {
    
    
        return new LoadData<>(model, new OkHttpStreamFetcher(client, model));
    }

    /**
     * The default factory for {@link OkHttpUrlLoader}s.
     */
    public static class Factory implements ModelLoaderFactory<GlideUrl, InputStream> {
    
    
        private static volatile Call.Factory internalClient;
        private Call.Factory client;

        private static Call.Factory getInternalClient() {
    
    
            if (internalClient == null) {
    
    
                synchronized (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(Call.Factory client) {
    
    
            this.client = client;
        }

        @Override
        public ModelLoader<GlideUrl, InputStream> build(MultiModelLoaderFactory multiFactory) {
    
    
            return new OkHttpUrlLoader(client);
        }

        @Override
        public void teardown() {
    
    
            // Do nothing, this instance doesn't own the client.
        }
    }
}

最后需要在mainfest 文件配置Module 路径

<application>
    <meta-data
            android:name="com.xx.xx.http.glide.OkHttpGlideModule"
            android:value="GlideModule" />
    </application>

猜你喜欢

转载自blog.csdn.net/Android_LeeJiaLun/article/details/129832542