Add Retrofit Requestinterceptor with Dagger at runtime

泄露秘密 提交于 2020-01-13 13:52:13

问题


I'm using dagger and retrofit. I inject my Retrofit services with Dagger.

Now i wanna do a authorization request to get an accessToken.

Afterwards i want to enhance my api module with an Request interceptor to use this access token for future requests.

My idea is to use the ObjectGraph.plus() method after i received the access token, but i'm not sure if this is the best way to do it.

Can someone point me to the right direction or maybe is there an example project on github ?


回答1:


The key is to always add the RequestInterceptor and then change whether or not it adds the header.

class ApiHeaders implements RequestInterceptor {
  private String authValue;

  public void clearAuthValue() {
    authValue = null;
  }

  public void setAuthValue(String authValue) {
    this.authValue = authValue;
  }

  @Override public void intercept(RequestFacade request) {
    String authValue = this.authValue;
    if (authValue != null) {
      request.addHeader("Authorization", authValue);
    }
  }
}

This way you can inject your ApiHeaders singleton when you need to set or clear the token.



来源:https://stackoverflow.com/questions/27868511/add-retrofit-requestinterceptor-with-dagger-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!