Glide定制--使用Okhttp3替换默认HttpURLConnection,实现添加请求头等需求

在Android开发中,第三方图片加载库使用广泛,功能强大,其中Glide就是一款非常强大的图片加载库,关于此库的一些用法网上比比皆是,这里提一下的是Glide默认使用的是HttpURLConnection进行网络请求,在其Gitgub上的文档表明,我们可以使用Okhttp、Volley等替换原有的网络请求方式。

使用方式:

添加Gradle依赖:

 dependencies {
    compile 'com.github.bumptech.glide:okhttp3-integration:1.5.0@aar'
    //compile 'com.squareup.okhttp3:okhttp:3.2.0'
    // but should be compatible with latest as well, if you want to override it
}

在Github上,我们可以看到,在Okhttp3的支持包里,有以下代码:

@Deprecated
public class OkHttpGlideModule implements GlideModule {
  ...

  @Override
  public void registerComponents(Context context, Registry registry) {
    //使用定义的OkhttpClient替换原有的请求
    registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory());
  }
}

接下来我们看OkHttpUrlLoader这个类里都具体做了什么:

/**
 * A simple model loader for fetching media over http/https using OkHttp.
 */
public class OkHttpUrlLoader implements ModelLoader<GlideUrl, InputStream> {
  //定义的Client
  private final Call.Factory client;

  ...

  @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;
    }

   ...

  }
}

这里我们看到,主要提供了两种方法,来设置OkhttpClient,而在OkHttpGlideModule中,使用的是默认的OkhttpClient,该Client没有任何自定义的行为,所以我们要实现添加请求头的目的,就需要写一个子类,继承OkHttpGlideModule,并重写registerComponents()方法,设置我们自定义的OkhttpClient:

public class MyOkHttpGlideModule extends OkHttpGlideModule {
    @Override
    public void registerComponents(Context context, Glide glide) {
        //定制OkHttp
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();

        //请求头设置
        httpClientBuilder.interceptors().add(new HeadInterceptor());

        OkHttpClient okHttpClient = httpClientBuilder.build();
        glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okHttpClient));
    }


    public static class HeadInterceptor implements Interceptor {

        public HeadInterceptor() {
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request.Builder request = chain.request().newBuilder();

            //这里添加我们需要的请求头
            request.addHeader("Referer", "http://www.baidu.com");
            return chain.proceed(request.build());
        }
    }
}

定义好之后,在Manifest.xml中,添加需要的<meta-data>:

<application>

        ...

         <meta-data
                    android:name="{packageName}.MyOkHttpGlideModule"
                    android:value="GlideModule" />
</application>

其他代码不用动,接下来,我们使用Glide进行网络请求时,就会有请求头了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,560评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,993评论 19 139
  • 一、简介 在泰国举行的谷歌开发者论坛上,谷歌为我们介绍了一个名叫Glide的图片加载库,作者是bumptech。这...
    天天大保建阅读 7,593评论 2 28
  • 和70%的大家一样,我也在追这部“大尺度神剧”《人民的名义》,久违的国产剧,意外的反腐剧,现实的内涵剧。今天不谈剧...
    言语嫣然阅读 729评论 0 0
  • 最不喜欢的感觉就是,当与一个人交谈时,他说了某句话你只是反驳了一句,他就会回一句“我不就开玩笑吗,你至于这么当真这...
    七同学阅读 191评论 0 0