Answer the question
In order to leave comments, you need to log in
How to update Interceptor in OkHttp when using Retrofit?
How to update Interceptor in OkHttp when using Retrofit?
@Provides
@Singleton
OkHttpClient provideOkhttpClient(Cache cache) {
return new OkHttpClient.Builder()
.cache(cache)
.addInterceptor(new AddCookiesInterceptor(mApplication))
.addInterceptor(new ReceivedCookiesInterceptor(mApplication))
.addInterceptor(provideHeaderTokenInterceptor(mApplication))
.addInterceptor(provideHttpLoggingInterceptor())
.build();
}
@Provides
@Singleton
Retrofit provideRetrofit(OkHttpClient okHttpClient) {
return new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(mBaseUrl)
.client(okHttpClient)
.build();
}
@Provides
HeaderTokenInterceptor provideHeaderTokenInterceptor(Context context) {
String token = Prefs.load(context, Prefs.PREFS_TOKEN);
if (token != null && !token.isEmpty()) {
return new HeaderTokenInterceptor(AppConstants.TOKEN_JWT + token);
} else {
return new HeaderTokenInterceptor("");
}
}
Answer the question
In order to leave comments, you need to log in
You can override the intercept() method and add a header with a token in it:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request original = chain.request();
String token = ""; // Get token from prefs
if (!TextUtils.isEmpty(token)) {
Request.Builder requestBuilder = original.newBuilder()
.addHeader("Token", token);
Request request = requestBuilder.build();
return chain.proceed(request);
} else {
return chain.proceed(original);
}
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question