gpt4 book ai didi

android - 将所有正在进行的请求放入队列改造和 okhttp

转载 作者:行者123 更新时间:2023-11-29 17:13:46 25 4
gpt4 key购买 nike

我正在使用 authenticator OKHttp如果我们得到 401,它将重试获取新的访问 token 状态错误,但我的应用程序必须同时调用许多 API,导致数据损坏,因为现有的刷新 token 将在请求时被删除 - 但其他 API 调用者仍然依赖此 token 来使用。所以我的问题是:当我们收到 401 错误状态代码时,是否可以将请求放入队列(或至少取消)所有其他 api 请求?

这是我的验证器:

 public Request authenticate(Route route, Response response) throws IOException {
// Refresh your access_token using a synchronous api request
access_token = getNewAccessTokenHere();
// Add new header to rejected request and retry it
return response.request().newBuilder()
.header("Authorization", "Bearer " + access_token)
.build();
} else {
ToastUtil.toast("login again");
return null;
}

}

我的目标是让其他 api 等待第一个请求的响应并使用新的 access_token。

最佳答案

我知道这个问题很老了,但我最近发现自己遇到了同样的问题,我找到了一个对我有用的解决方案,我相信它可以帮助处于同样情况的其他人。

附加 Dispatcher 的解决方案到 OkHttp 客户端并限制最大请求量似乎不适用于开箱即用的改造,如 Jake Wharthon 所述.

所以我的解决方案是在我的自定义 Authenticator同步 authenticate 方法,对我的单例 Retrofit 实例进行并发调用,等待每个线程的身份验证例程完成。这样,带有未授权响应的第一个调用可以刷新 token 并通知下一个调用,也有未授权响应,新的访问 token 已经可用。

public class MyAuthenticator implements Authenticator {

private boolean isRefreshed = false;


// Call when a new request is being made. Concurrent request should call this method to enable the refresh routine
public void newRequest(){
isRefreshed = false;
}

@Nullable
@Override
public synchronized Request authenticate(@NonNull Route route, @NonNull Response response) throws IOException { // Synchronize the method to avoid refreshing thread overlapping
if (responseCount(response) > 3) {
return null;
}

if (!isRefreshed){
// Refresh your access_token using a synchronous api request
String accessToken = getNewAccessTokenHere();

// Saves the new access token
saveNewAccessToken(accessToken);
isRefreshed = true;

// Add new header to rejected request and retry it
return response.request().newBuilder()
.removeHeader("Authorization") // removes the old header, avoiding duplications
.addHeader("Authorization", "Bearer " + accessToken)
.build();

}
else{ // Access token already refreshed so retry with the new one

// Get the saved access token
String accessToken = getAccessToken();

return response.request()
.newBuilder()
.removeHeader("Authorization")
.addHeader("Authorization", accessToken)
.build();
}

}

private int responseCount(Response response) {
int result = 1;
while ((response = response.priorResponse()) != null) {
result++;
}
return result;
}

关于android - 将所有正在进行的请求放入队列改造和 okhttp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39867878/

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