Trong ứng dụng của tôi, tôi đã triển khai Retrofit để gọi WebServices và tôi đang sử dụng OkHttp để sử dụng Interceptor và Authenticator. Một số yêu cầu cần token và tôi đã triển khai giao diện Authenticator để xử lý việc làm mới (theo chính thức documentation). Nhưng tôi có vấn đề sau: theo thời gian trong ứng dụng của tôi, tôi phải gọi nhiều hơn một yêu cầu cùng một lúc. Do đó, đối với một trong số họ, tôi sẽ gặp lỗi 401.OkHttp và Retrofit, mã thông báo làm mới với các yêu cầu đồng thời
Đây là mã của tôi cho các cuộc gọi yêu cầu:
public static <S> S createServiceAuthentication(Class<S> serviceClass, boolean hasPagination) {
final String jwt = JWT.getJWTValue(); //Get jwt value from Realm
if (hasPagination) {
Gson gson = new GsonBuilder().
registerTypeAdapter(Pagination.class, new PaginationTypeAdapter()).create();
builder =
new Retrofit.Builder()
.baseUrl(APIConstant.API_URL)
.addConverterFactory(GsonConverterFactory.create(gson));
}
OkHttpClient.Builder httpClient =
new OkHttpClient.Builder();
httpClient.addInterceptor(new AuthenticationInterceptor(jwt));
httpClient.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
if (responseCount(response) >= 2) {
// If both the original call and the call with refreshed token failed,
// it will probably keep failing, so don't try again.
return null;
}
if (jwt.equals(response.request().header("Authorization"))) {
return null; // If we already failed with these credentials, don't retry.
}
APIRest apiRest = createService(APIRest.class, false);
Call<JWTResponse> call = apiRest.refreshToken(new JWTBody(jwt));
try {
retrofit2.Response<JWTResponse> refreshTokenResponse = call.execute();
if (refreshTokenResponse.isSuccessful()) {
JWT.storeJwt(refreshTokenResponse.body().getJwt());
return response.request().newBuilder()
.header(CONTENT_TYPE, APPLICATION_JSON)
.header(ACCEPT, APPLICATION)
.header(AUTHORIZATION, "Bearer " + refreshTokenResponse.body().getJwt())
.build();
} else {
return null;
}
} catch (IOException e) {
return null;
}
}
});
builder.client(httpClient.build());
retrofit = builder.build();
return retrofit.create(serviceClass);
}
private static int responseCount(Response response) {
int result = 1;
while ((response = response.priorResponse()) != null) {
result++;
}
return result;
}
Vấn đề là đơn giản, yêu cầu đầu tiên sẽ làm mới thẻ thành công nhưng những người khác sẽ thất bại bởi vì họ sẽ cố gắng để làm mới một mã thông báo đã làm mới. WebService trả về lỗi 500. Có giải pháp thanh lịch nào để tránh điều này không?
Cảm ơn bạn!
Điều này có thể giúp bạn, hy vọng nó không quá muộn https://stackoverflow.com/a/48518733/8187386 –