OkHttp和Retrofit,使用并发请求刷新令牌

编程入门 行业动态 更新时间:2024-10-25 20:23:45
本文介绍了OkHttp和Retrofit,使用并发请求刷新令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在我的应用程序中,我实现了Retrofit来调用WebServices,并且我使用OkHttp来使用Interceptor和Authenticator.有些请求需要令牌,并且我已经实现了Authenticator接口来处理刷新(以下是官方的文档).但是我有以下问题:在我的应用程序中,我不得不一次调用多个请求.因此,对于其中之一,我将出现401错误.

In my application I implemented Retrofit to call WebServices and I'm using OkHttp to use Interceptor and Authenticator. Some requests need token, and I have implemented Authenticator interface to handle the refresh (following the official documentation). But I have the following issue : time to time in my app I have to call more than one request at once. Because of that, for one of them I will have the 401 error.

这是我的请求代码:

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; }

问题很简单,第一个请求将成功刷新令牌,但其他请求将失败,因为其他人将尝试刷新已刷新的令牌. WebService返回错误500.是否有任何优雅的解决方案来避免这种情况?

The issue is simple, the first request will refresh the token successfully but others will failed because they will try to refresh a token already refreshed. The WebService return an error 500. Is there any elegant solution to avoid this ?

谢谢!

推荐答案

如果我了解您的问题,则在更新令牌时会发送一些请求,这会给您带来错误.

If I understand your issue, some requests are sent while the token is being updated, this gives you an error.

您可以尝试在更新令牌(带有已同步"对象)时阻止所有请求,但这不能解决已经发送的请求的情况.

You could try to prevent all the requests while a token is being updated (with a 'synchronized' object) but this will not cover the case of an already sent request.

由于很难完全避免该问题,因此此处正确的方法可能是具有良好的后备行为.例如,通过使用更新的令牌重新运行请求,来处理在令牌更新期间发出请求时遇到的错误.

Since the issue is difficult to avoid completely, maybe the right approach here is to have a good fallback behavior. Handling the error you get when you've made a request during a token update by re-running the request with the updated token for instance.

更多推荐

OkHttp和Retrofit,使用并发请求刷新令牌

本文发布于:2023-11-06 09:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563352.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:令牌   OkHttp   Retrofit

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!