Reputation: 144
I'm using Retrofit2 to make requests to server.
The problem is: sometimes the server will return code 401 for every request from an user. If the user get this code, he should be immediately kicked out from the app (logged out and not be able to do anything before re-login).
So for every request that being sent to the server, I want to check if the server response this code. It's not beautiful writing this check in all the request calls, so I want to write this check only one and it will perform every time user makes request!
Upvotes: 3
Views: 1824
Reputation: 29436
Retrofit (current release) needs an HTTP client to make requests. OkHttp library by same developer comes bundled with Retrofit as default client. OkHttp
supports adding Interceptor
's to the client which can intercept request execution.
For Example:
import android.util.Log;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class ErrorInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
// before request
Request request = chain.request();
// execute request
Response response = chain.proceed(request);
// after request
// inspect status codes of unsuccessful responses
switch (response.code()){
case 401:
// do something else
Log.e("TEST","Unauthorized error for: " +request.url());
// perhaps throw a custom exception ?
throw new IOException("Unauthorized !!");
}
return response;
}
}
To use it, include it in OkHttpClient
that Retrofit
instance uses:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new ErrorInterceptor())
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl("/")
.build();
So, you can implement an Interceptor
for each "global logic" or "cross-cutting concern" and add them all in a sequence to Retrofit.
Upvotes: 4
Reputation: 566
If you need check "401" code there is special object in OkHttp for it: Authenticator (Recipes in OkHttp). For example:
public class RefreshTokenAuthenticator implements Authenticator {
@Override
public Request authenticate(Route route, Response response) throws IOException {
// You get here, if response code was 401.
// Then you can somehow change your request or data in your app in this method and resend your request.
Request request = response.request();
HttpUrl url = request.url().newBuilder()
.setQueryParameter("access_token", "new_access_token_may_be")
.build();
request = request.newBuilder()
.url(url)
.build();
return request;
}
}
Upvotes: 2