简体   繁体   English

Okhttp Authenticator具有多个异步API调用

[英]Okhttp Authenticator with multiple asynchronous API calls

I am facing an API with a token refresh system implemented. 我正面临着一个带有令牌刷新系统的API。 I am using Retrofit for the API requests and I have set an Authenticator to detect when an Error 401 is given and make new request to refresh the token. 我正在使用Retrofit进行API请求,我设置了一个Authenticator来检测何时给出Error 401并发出刷新令牌的新请求。

The problem is that if the app has multiple requests at the same time (for instance, to fill multiple pages in a ViewPager or in an API request in a Service while user is using the app and cause another API request), the API is responding with 401 multiple times and, because of that, the application is requesting the Authenticator multiple times. 问题是,如果应用程序同时有多个请求(例如,在用户使用应用程序并导致另一个API请求时填充ViewPager中的多个页面或Service API请求),则API正在响应多次使用401,因此,应用程序多次请求Authenticator

How do you manage to fix that? 你是如何解决这个问题的? I'm thinking about a Singleton with a boolean to detect if the application is doing a token refresh call but it doesn't seems to me the best way to achieve it. 我正在考虑一个带有booleanSingleton来检测应用程序是否在进行令牌刷新调用,但在我看来这不是实现它的最佳方法。

I would say Singleton is a good idea, but by Singleton I mean having a credentials object inside api client object - it would be singleton in object scope instead of whole application scope. 我会说Singleton是一个好主意,但是Singleton我的意思是在api客户端对象中有一个凭证对象 - 它在对象范围内是单例,而不是整个应用程序范围。 You'd recommend doing something similar to this answer 你建议做一些类似于这个答案的事情

I would introduce new object to be used as a semafore - it would be blocked every time when 'credentials are being refreshed'. 我将介绍用作semafore的新对象 - 每次“刷新凭据”时它都会被阻止。 To make sure that you'll make only one 'refresh credentials' call, you need to call it in block of code which is synchronized with object. 为了确保您只进行一次'刷新凭证'调用,您需要在与对象同步的代码块中调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM