2016-11-16 32 views
1

我一直想采取匕首2共轭与改造2.一切似乎除了GET要求很好地工作;他们似乎没有附加任何标题。不能得到改造2用匕首发送全局套头2

下面是我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 

我错过了什么吗?

+0

从这里看看你更好理解https://github.com/saveendhiman/SampleApp/blob/master/app/src/main/java/com/sampleapp/api/NetModule.java – Saveen

+0

@Raghunandan,isn' t addNetworkInterceptor'已经做了什么?那么,不完全是这个方法,而是传入的'Interceptor'。 –

+0

我现在看到了。抱歉! – Raghunandan

回答

0

使用.addInterceptor代替.addNetworkInterceptor()

+0

试过了,什么都没发生。 –

0

首先使用addInterceptor()像亚历克斯Shutov建议。

其次,确保在调试模式下调用方法addHeader()被调用。 如果使用相同的改造实例(同一注射)它不能使用,因为loginSessionPreference.isSet()始终返回false。

你的方法provideOkHttp()时调用了OkHttpClient有必要提供改造实例。方法provideOkHttp()要求偏好并且它注入时对象OkHttpClient创建。你可以把它看作是一个最终的变量(编译器甚至会让它最终成为我认为的)。

请删除loginSessionPreference逻辑和硬编码一些标题 - 它会告诉我们,如果这是问题。

在我看来,你需要改变这个架构一点。