When I get the status code 401 in the API, then I have to open the login activity . I donβt want to introduce change logic into every onError API method. I want a global method that is used for all APIs. Therefore, for this I created one Interceptor
public class MyInterceptor extends BaseActivity implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
if (response.code() == 401) {
throw new RuntimeException(" Here you got 401 from API !");
}
return response;
}
}
Here I add this Interceptor
OkHttpClient.Builder builder=new OkHttpClient.Builder()
.addNetworkInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Content-Type", "application/json")
.addHeader("User-Agent", "MyApp-Android-App")
.build();
return chain.proceed(newRequest);
}
})
.addNetworkInterceptor(new StethoInterceptor())
.addNetworkInterceptor(new MyInterceptor())
.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
Now, where should I add a method to call activity changes. Another thing I call an API with RxRetrofit. I want a global method to handle this 401 response . Can you provide me any solution where I should put the activity change method?