2016-11-16 31 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邏輯和硬編碼一些標題 - 它會告訴我們,如果這是問題。

在我看來,你需要改變這個架構一點。