N
N
newdancer2018-07-01 16:50:28
Android
newdancer, 2018-07-01 16:50:28

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("");
        }
    }

I use provideHeaderTokenInterceptor to add a token when making requests. But here, for example, I do authorization without a token, in response I get a token. I save the token. But when making requests, it is not used because provideHeaderTokenInterceptor is no longer called, but the existing one is used. How can I fix it?
Now restarting the app helps.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
acbelter, 2018-07-19
@newdancer

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 question

Ask a Question

731 491 924 answers to any question