gpt4 book ai didi

android - Okhttp Authenticator addHeader() vs header()

转载 作者:行者123 更新时间:2023-12-05 00:13:47 32 4
gpt4 key购买 nike

在使用拦截器和身份验证器添加访问 token header 时,当服务器以 401 响应时,我的身份验证器被正确调用。

Authenticator 通过单独的网络调用更新访问 token 并将其设置在 header 中以重试。代码将非常相似 to this sample

我刚刚花了一个小时弄清楚我使用错误的方法将更新的 token 添加到身份验证器, 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 :

Sets the header named {@code name} to {@code value}. If this request already has any headers with that name, they are all replaced.


addHeader :

Adds a header with {@code name} and {@code value}. Prefer this method for multiply-valued headers like "Cookie". Note that for some headers including {@code Content-Length} and {@code Content-Encoding}, OkHttp may replace {@code value} with a header derived from the request body.



所以 header如果已添加,将替换,而 addHeader一般不会。

关于android - Okhttp Authenticator addHeader() vs header(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57872635/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com