【发布时间】:2017-03-30 11:11:27
【问题描述】:
我一直想将 Dagger 2 与 Retrofit 2 结合使用。除了GET 请求之外,一切似乎都运行良好;他们似乎没有附加任何标题。
下面是我的NetworkModule,它为整个应用程序提供了所有与网络相关的依赖项(注意@ForApplication 范围注释散布在那里):
@Module
public class NetworkModule {
// …
@ForApplication
@Provides
OkHttpClient provideOkHttp(
HttpLoggingInterceptor loggingInterceptor,
@Named(PREFERENCE_CUR_LOGIN_SESSION) Preference<LoginSession> loginSessionPreference,
DeviceCredentials deviceCredentials
) {
final OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
builder.addNetworkInterceptor(chain -> {
if (loginSessionPreference.isSet()) {
return chain.proceed(
chain.request().newBuilder()
.addHeader("token", loginSessionPreference.get().getTokenId())
.addHeader("device-id", deviceCredentials.getDeviceId())
.addHeader("Content-Type", "application/json")
.build()
);
} else {
return chain.proceed(
chain.request().newBuilder().build()
);
}
});
return builder.build();
}
@ForApplication
@Provides
Retrofit provideRetrofit(Gson gson, OkHttpClient client) {
return new Retrofit.Builder()
.baseUrl("http://xxx.xxx.xxx/api/1.0/")
.client(client)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
@ForApplication
@Provides
XxxApi provideApi(Retrofit retrofit) {
return retrofit.create(XxxApi.class);
}
}
这个模块是作为我的ApplicationComponent(以及其他模块)的依赖项提供的:
@ForApplication
@Component(
modules = {
ApplicationModule.class,
RuntimeModule.class,
DateFormatModule.class,
PreferenceModule.class,
NetworkModule.class
}
)
public interface ApplicationComponent {
// …
}
我已经运行了一个调试会话并确认loginSessionPreference.isSet() 被评估为true,但我的请求仍然显示没有任何标题:
11-16 16:55:22.748 21747-22569/xxx.xxx.xxx D/OkHttp: --> GET http://xxx.xxx.xxx/api/1.0/public/get-all-data/site http/1.1
11-16 16:55:22.748 21747-22569/xxx.xxx.xxx D/OkHttp: --> END GET
我错过了什么吗?
【问题讨论】:
-
@Raghunandan,这不是
addNetworkInterceptor已经做的吗?嗯,不完全是方法,而是传入的Interceptor。 -
我现在看到了。对不起!
标签: android retrofit2 dagger-2 okhttp3