android - 如何在 Glide 库中设置代理
问题描述
我正在使用捆绑在我的应用程序中的 Psiphon vpn,因此所有 REST 调用都通过本地端口。
我已经向OkHttp
客户端添加了一个代理,Retrofit
如下所示:
OkHttpClient.Builder client =
new OkHttpClient.Builder().proxy(new Proxy(Proxy.Type.HTTP,
new InetSocketAddress("localhost", randomPort )));
builder.client(client.build());
retrofit = builder.build();
到目前为止一切正常,我可以通过本地代理成功加载所有文本内容,但由于 Glide 有自定义连接,图像没有加载。
现在我想为 Glide 或任何其他用于图像加载的库设置类似于上述代码的代理
我正在使用 Glide “4.8.0”,就像这样:
Glide.with(this)
.load(image_url)
.into(miniImageView);
解决方案
我使用自定义做到了@GlideModule
将以下行添加到应用程序中build.gradle
implementation 'com.github.bumptech.glide:glide:4.8.0'
implementation('com.github.bumptech.glide:okhttp3-integration:4.8.0') {
exclude group: 'glide-parent'
}
implementation 'com.github.bumptech.glide:annotations:4.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
这是我的自定义模块:
@GlideModule
public class CustomGlideModule extends AppGlideModule {
@Override
public void registerComponents(Context context, Glide glide, Registry registry) {
Builder builder = new Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS);
if (VpnService.connected) {
builder.proxy(VpnService.proxy);
}
OkHttpClient client = builder.build();
OkHttpUrlLoader.Factory factory = new OkHttpUrlLoader.Factory(client);
glide.getRegistry().replace(GlideUrl.class, InputStream.class, factory);
}
}
@GlideModule
Glide 会在类的顶部自动检测到它,并在运行时注入它。现在 Glide 的每个图像加载都将通过我的自定义模块和自定义 OkHttp 连接
推荐阅读
- swift - Swift - 使用 for 循环读取嵌套结构
- sas - 灵活创建SAS表头
- tensorflow - Estimator 的 model_fn 包含 params 参数,但 params 不会传递给 Estimator
- ios - 在 WebView 中加载大尺寸文件 (xls) 时应用程序崩溃
- c# - 我可以在播放模式下运行 BuildPipeline.BuildAssetBundles 吗?
- android - 无法在 Android 中创建第二个 SQLite 表
- c# - 如何在 C# 中反序列化 xml?
- jquery - jQuery:如果内容更改为某些文本,则执行某些操作
- python - 如何保存在数据库中
- wpf - 在 WPF 中,是否存在“渲染完成”事件?