Glide定制--使用Okhttp3替換默認(rèn)HttpURLConnection,實現(xiàn)添加請求頭等需求

在Android開發(fā)中,第三方圖片加載庫使用廣泛,功能強(qiáng)大,其中Glide就是一款非常強(qiáng)大的圖片加載庫,關(guān)于此庫的一些用法網(wǎng)上比比皆是,這里提一下的是Glide默認(rèn)使用的是HttpURLConnection進(jìn)行網(wǎng)絡(luò)請求,在其Gitgub上的文檔表明,我們可以使用Okhttp、Volley等替換原有的網(wǎng)絡(luò)請求方式。

使用方式:

添加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;
    }

   ...

  }
}

這里我們看到,主要提供了兩種方法,來設(shè)置OkhttpClient,而在OkHttpGlideModule中,使用的是默認(rèn)的OkhttpClient,該Client沒有任何自定義的行為,所以我們要實現(xiàn)添加請求頭的目的,就需要寫一個子類,繼承OkHttpGlideModule,并重寫registerComponents()方法,設(shè)置我們自定義的OkhttpClient:

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

        //請求頭設(shè)置
        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進(jìn)行網(wǎng)絡(luò)請求時,就會有請求頭了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,319評論 25 708
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,688評論 19 139
  • 一、簡介 在泰國舉行的谷歌開發(fā)者論壇上,谷歌為我們介紹了一個名叫Glide的圖片加載庫,作者是bumptech。這...
    天天大保建閱讀 7,786評論 2 28
  • 和70%的大家一樣,我也在追這部“大尺度神劇”《人民的名義》,久違的國產(chǎn)劇,意外的反腐劇,現(xiàn)實的內(nèi)涵劇。今天不談劇...
    言語嫣然閱讀 881評論 0 0
  • 最不喜歡的感覺就是,當(dāng)與一個人交談時,他說了某句話你只是反駁了一句,他就會回一句“我不就開玩笑嗎,你至于這么當(dāng)真這...
    七同學(xué)閱讀 201評論 0 0

友情鏈接更多精彩內(nèi)容