I use Retrofit to handle communication with the server API, a user of the JSON APIs for authentication. The token expires from time to time, and I'm looking for the best way to implement a Retrofit Client, which can update the token automatically when it expires.
This is the initial implementation I came with:
public class RefreshTokenClient extends OkClient { private static final int UNAUTHENTICATED = 401; private Application mContext; public RefreshTokenClient(OkHttpClient client, Application application) { super(client); mContext = application; } @Override public Response execute(Request request) throws IOException { Timber.d("Execute request: " + request.getMethod() + " - " + request.getUrl());
I do not know the architecture of Retrofit / OkHttpClient very well, but as far as I understand, the execute method can be called several times from several threads, OkClient is the same common for Calls that only a small copy is made. I use the synchronized method in refreshToken() to avoid multiple threads to enter refreshToken() and make several calls to enter the system, only the update is required, only one thread needs to do refreshCall, and the rest will use the updated token.
I have not experienced this seriously yet, but for what I see, it works fine. Maybe someone had this problem and can share their solution, or it might be useful for someone with the same / similar problem.
Thanks.
Sergio serra
source share