Mr.D
Mr.D

Reputation: 7873

Android, Retrofit catch specific response code for all requests

I have Retrofit Rest client interface with more than 40 http calls. I initialize my RestClient like this:

public class RestClient {

    private static final String BASE_URL = "http://example.com/";

    private static final int TIMEOUT_IN_SECONDS = 30;

    private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .addInterceptor(getInterceptor())
        .connectTimeout(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
        .readTimeout(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
        .writeTimeout(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
        .build();


    private static Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build();

    private RestClient() {

    }

    private static HttpLoggingInterceptor getInterceptor() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY
            : HttpLoggingInterceptor.Level.NONE);
        return interceptor;
    }

    public static MyService request() {
        return retrofit.create(MyService.class);
    }

}

All requests, except authorization, requires special token. When this token expires REST API responds with 403 code error.

I can't add checking for this code response from each of my API call, because there are more than 100 api calls in my application.

Is it possible to somehow catch 403 response code in the level of my RestClient class so I could open Authorization Activity again?

Upvotes: 0

Views: 1591

Answers (1)

duan
duan

Reputation: 56

First, I think 403 is wrong, 401 may be right. If you are sure When this token expires REST API responds with 403 code error. You can't use Authenticator which will be used when 401 happens. So, you need use Interceptor. you can create TokenInterceptor implements Interceptor

public class TokenInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (response.code() == 403) {
            doSomething();
        }
        return response;
    }
}

okHttpClient add this TokenInterceptor.

Upvotes: 3

Related Questions