本文介绍了在运行时添加带有Dagger的Retrofit Requestinterceptor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用匕首和改型.我向Dagger注入了Retrofit服务.

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

现在,我想发出授权请求以获取accessToken.

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

此后,我想使用请求拦截器增强我的api模块,以便将此访问令牌用于将来的请求.

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

我的想法是在收到访问令牌后使用ObjectGraph.plus()方法,但是我不确定这是否是最好的方法.

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.

有人可以指出我正确的方向吗,或者github上是否有示例项目?

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

推荐答案

关键是始终添加RequestInterceptor,然后更改是否添加标题.

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

通过这种方式,您可以在需要设置或清除令牌时注入ApiHeaders单身人士.

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

这篇关于在运行时添加带有Dagger的Retrofit Requestinterceptor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 19:36