Retrofit handling token expiration

纵然是瞬间 提交于 2021-01-29 10:01:20

问题


Right now im using Retrofit to fitch data from server. the problem is i need to call API to get new token every 1 hour, and so far im running background service to get new token before the 1 hour expire, and just in case if API response fail because of token expire i call the API token, than recall the method again.

My question: is there's build-in way in retrofit to handle token expiration? or anything similar.


回答1:


Retrofit is made to help YOU handle the requests you need. It doesn't handle token expiration. This means, that you need to handle that yourself. For example, in your request error handling, you can check for 401 error Unauthorized (this is usually the error a server sends when a token expires). When this occurs, hold the failed request and send another request for a new token. When the new request is successfully completed, you will have your token refreshed and you can retry the initial failed request with the newly fetched token.




回答2:


i think that u can use an OkHttp Interceptor to catch 401 Unauthorized for any request and than refresh your token and retry your request.

https://futurestud.io/tutorials/retrofit-2-catch-server-errors-globally-with-response-interceptor

Global Error Handler: OkHttp Interceptor



来源:https://stackoverflow.com/questions/52837981/retrofit-handling-token-expiration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!