无法通过Dagger 2发送Retrofit 2来发送全局设置的标头

时间:2016-11-16 09:57:07

标签: android retrofit2 dagger-2 okhttp3

我一直想要与Retrofit 2结合使用Dagger 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

我错过了什么吗?

2 个答案:

答案 0 :(得分:0)

使用.addInterceptor代替.addNetworkInterceptor()

答案 1 :(得分:0)

首先使用像Alex Shutov建议的 addInterceptor()

其次,在调试模式下确保调用方法 addHeader()。 如果您使用相同的 Retrofit 实例(相同注入),则无法使用它,因为 loginSessionPreference.isSet()始终返回false。

调用您的方法 provideOkHttp(),而 OkHttpClient 是提供 Retrofit 实例所必需的。方法 provideOkHttp()需要首选项,并在创建对象 OkHttpClient 时注入。你可以将它视为最终变量(编译器甚至让我认为它是最终的)。

请删除 loginSessionPreference 逻辑并对一些标题进行硬编码 - 它会告诉我们这是否是问题。

在我看来,你需要稍微改变这种架构。

相关问题