首页 > 解决方案 > 如何在 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);

标签: androidproxyandroid-glide

解决方案


我使用自定义做到了@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);
  }
}

@GlideModuleGlide 会在类的顶部自动检测到它,并在运行时注入它。现在 Glide 的每个图像加载都将通过我的自定义模块和自定义 OkHttp 连接


推荐阅读