改造处理令牌过期 [英] Retrofit handling token expiration

查看:137
本文介绍了改造处理令牌过期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在使用 Retrofit 从服务器获取数据.问题是我需要每 1 小时调用一次 API 来获取新令牌,到目前为止我正在运行后台服务以在 1 小时到期之前获取新令牌,以防万一 API 响应因令牌到期而失败,我调用 API 令牌,而不是再次回忆该方法.

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.

推荐答案

改造是为了帮助您处理您需要的请求.它不处理令牌过期.这意味着,您需要自己处理.例如,在您的请求错误处理中,您可以检查 401 错误 Unauthorized(这通常是服务器在令牌过期时发送的错误).发生这种情况时,保留失败的请求并发送另一个新令牌请求.新请求成功完成后,您的令牌将刷新,您可以使用新获取的令牌重试初始失败的请求.

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.

这篇关于改造处理令牌过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆