英文:
recall http request from intereceptor token is not valid
问题
我们在我们的API中使用令牌,当任何HTTP请求到达时,我们会检查令牌是否有效,如果令牌无效,我们会在拦截器中获取新的令牌。
if (resultObj.code == AppConstants.TOKEN_IS_NOT_ACTIVE)
getTokenOnce()
但是我应该如何获取该请求(可以是订单、报告等),然后重新将其发送到服务器?
英文:
we use token in our API , when any HTTP request we check if the token is active , if token is not active
we get new once in intereceptor
if (resultObj.code == AppConstants.TOKEN_IS_NOT_ACTIVE)
getTokenOnce()
but how can I get that request(which can be order,report... ) and post again to the server
答案1
得分: 1
以下是翻译好的内容:
目前你的 API 中如何进行令牌身份验证并不清楚,因此我将为你提供一个使用 Bearer 令牌身份验证类型的示例。
okhttp
拦截器的签名如下:
fun intercept(chain: Interceptor.Chain): Response
在 chain
中,您将找到原始请求。一个可能的方式如下:
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request
var response = chain.proceed(originalRequest)
if (response.code == AppConstants.TOKEN_IS_NOT_ACTIVE) {
val token = getTokenOnce()
val newRequest = originalRequest.newBuilder()
.header("Authorization", "Bearer $token")
.build()
response = chain.proceed(newRequest)
}
return response
}
因此,这里的想法是从原始请求创建一个新请求 - newBuilder()
- 并添加一个带有新令牌的标头。我假设 getTokenOnce
可以返回新令牌作为字符串。也许这需要稍作调整。
最后,您再次继续进行请求。
需要注意的一点是,在设置拦截器时,它需要设置为应用程序拦截器,而不是网络拦截器。网络拦截器不允许您多次进行请求。
英文:
It's not clear how you do the token authentication in your apis, so I'll just give you an example that uses a bearer token authentication type.
The signature for an okhttp interceptor is:
fun intercept(chain: Interceptor.Chain): Response
Inside chain
you'll find the original request. One way this might look like is:
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request
var response = chain.proceed(originalRequest)
if (response.code == AppConstants.TOKEN_IS_NOT_ACTIVE) {
val token = getTokenOnce()
val newRequest = originalRequest.newBuilder()
.header("Authorization", "Bearer $token")
.build()
response = chain.proceed(newRequest)
}
return response
}
So the idea here is to create a new request from the original one - newBuilder()
- and add a header with the new token. I assume that getTokenOnce
can return the new token as a string. Maybe this needs to be tweaked a bit.
Lastly, you proceed with the request again.
One thing to bear in mind is that while setting up the interceptors, it needs to be set as an application interceptor and not as a network interceptor. Network interceptors don't let you proceed more than once.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论