Dagger + Retrofit。在运行时添加auth头 [英] Dagger + Retrofit. Adding auth headers at runtime
问题描述
我想知道Dagger是否有办法知道在新数据可用时它应该重新创建一个对象。
I'm wondering if there is a way for Dagger to know that it should recreate an object when new data is available.
我所说的实例是我有改进的请求标题。在某些时候(当用户登录时),我得到一个令牌,我需要将其添加到改造的标题中以进行经过身份验证的请求。问题是,我留下了相同的未经验证的改造版本。这是我的注入代码:
The instance I am speaking of is with the request headers I have for retrofit. At some point (when the user logs in) I get a token that I need to add to the headers of retrofit to make authenticated requests. The issue is, I'm left with the same unauthenticated version of retrofit. Here's my injection code:
@Provides
@Singleton
OkHttpClient provideOkHttpClient(Cache cache) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.cache(cache).build();
client
.newBuilder()
.addInterceptor(
chain -> {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.addHeader("Accept", "Application/JSON");
Request request = requestBuilder.build();
return chain.proceed(request);
}).build();
return client;
}
@Provides
@Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxErrorHandlingCallAdapterFactory.create())
.baseUrl(mBaseUrl)
.client(okHttpClient)
.build();
return retrofit;
}
@Provides
@Singleton
public NetworkService providesNetworkService(Retrofit retrofit) {
return retrofit.create(NetworkService.class);
}
有关如何使这项工作的任何想法?
Any ideas on how to make this work?
推荐答案
请考虑使用提及的方法 strong> @oldergod ,因为它是官方并且更好的方式,而下面提到的方法是不建议,它们可能被视为解决方法。
Please consider using the approach mentioned by @oldergod as it is the "official" and much better way, whereas the approaches mentioned below are not advised, they may be considered as workarounds.
您有几个选择。
- 一旦获得令牌,就必须将提供
Retrofit
实例的组件归零,创建一个新组件并要求新的Retrofit
实例,将使用必要的okhttp
实例进行实例化。 - 快速和坏的 - 在
SharedPreferences
中保存令牌,创建okHttp
标头,这将从<$ c $应用令牌读取C> SharedPreferences 。如果没有 - 发送没有令牌标题。 - 甚至更丑陋的解决方案 - 声明一个
静态volatile字符串
字段,并执行相同的操作就像在第2步中一样。
- As soon as you get the token, you have to null out the component that provided you the
Retrofit
instance, create a new component and ask for a newRetrofit
instance, which will be instantiated with necessaryokhttp
instance. - A fast and bad one - Save the token in
SharedPreferences
, createokHttp
header, which will apply token reading fromSharedPreferences
. If there is none - send no token header. - Even uglier solution - declare a
static volatile String
field, and do the same thing like in step 2.
为什么第二个选项不好?因为在每个请求中,您将轮询SD卡并从那里获取数据。
Why the second option is bad? Because on each request you would be polling SD card and fetch data from there.
这篇关于Dagger + Retrofit。在运行时添加auth头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!