App中的Dagger2实现
网络组件模块
@Provides
@Singleton
OkHttpClient provideOkHttpClient() {
return new OkHttpClient.Builder().addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder()
.addHeader("Accept", "application/json")
.addHeader("Client-Id", Constants.CONFIG.APP_NAME)
.addHeader("RE-Phone-Number", phoneNumber)
.addHeader("RE-Access-Token", access_token);
Request request = builder.build();
return chain.proceed(request);
}
}).build();
}
在app的beginnig上调用一次。我需要在获取后更改用户凭据。
@Provides
@Singleton
Retrofit provideRetrofit(GsonConverterFactory gsonConverterFactory,
RxJavaCallAdapterFactory rxJavaCallAdapterFactory,
OkHttpClient okHttpClient) {
return new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(gsonConverterFactory)
.addCallAdapterFactory(rxJavaCallAdapterFactory)
.build();
}
Api组件的模块
@Module
public class ApiModule {
@Provides
@PerFragment
CompanyService provideCompanyService(Retrofit retrofit){
return retrofit.create(CompanyService.class);
}
}