【发布时间】:2020-01-12 07:40:46
【问题描述】:
在使用拦截器和身份验证器添加访问令牌标头时,我的身份验证器在服务器响应 401 时正确调用。
身份验证器通过单独的网络调用更新访问令牌并将其设置在标头中以重试。代码将非常相似to this sample
我花了一个小时才发现我使用错误的方法将更新的令牌添加到身份验证器 addHeader vs header。
作品:
if (accessToken != null){
// retry the failed 401 request with new access token
return response.request().newBuilder()
.header("Authorization", accessToken) // use the new access token
.build();
}
不起作用:
if (accessToken != null){
// retry the failed 401 request with new access token
return response.request().newBuilder()
.addHeader("Authorization", accessToken) // use the new access token
.build();
}
这里可能发生了什么以及为什么addHeader() 的行为与header() 不同
【问题讨论】:
-
header()在每次 API 调用时更新其name的现有标头,而addHeader在标头列表中添加一个新标头,同时保留先前具有无效授权的标头。跨度>
标签: android retrofit2 okhttp restful-authentication