osama-raddad
12/27/2016 - 6:00 PM

Sample use of OkHttp + Retrofit Application Interceptor for Resending Requests w/ Refreshed Tokens

Sample use of OkHttp + Retrofit Application Interceptor for Resending Requests w/ Refreshed Tokens


        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.interceptors().add(mRefreshAndRetryInterceptor);

        mRestAdapter = new RestAdapter.Builder()
            ...
            .setClient(new OkClient(okHttpClient))
            .build();

        private final Interceptor mRefreshAndRetryInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();

                Response response = chain.proceed(request);

                if (response.code() == 401) {
                    Request newRequest = reWriteRequestWithNewToken(request);
                    response = chain.proceed(newRequest);
                }

                return response;
            }
        };