Android的OkHttp,刷新令牌过期 [英] Android OkHttp, refresh expired token

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

问题描述

场景:我使用OkHttp /改造来访问Web服务:多个HTTP请求在同一时间发送出去。在某一点上的身份验证令牌过期,并且多个请求会得到一个401响应。

Scenario: I am using OkHttp / Retrofit to access a web service: multiple HTTP requests are sent out at the same time. At some point the auth token expires, and multiple requests will get a 401 response.

问题:在我第一次执行我使用拦截器(这里简化),每个线程试图刷新令牌。这导致了一个烂摊子。

Issue: In my first implementation I use an interceptor (here simplified) and each thread tries to refresh the token. This leads to a mess.

public class SignedRequestInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        // 1. sign this request
        request = request.newBuilder()
                    .header(AUTH_HEADER_KEY, BEARER_HEADER_VALUE + token)
                    .build();


        // 2. proceed with the request
        Response response = chain.proceed(request);

        // 3. check the response: have we got a 401?
        if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {

            // ... try to refresh the token
            newToken = mAuthService.refreshAccessToken(..);


            // sign the request with the new token and proceed
            Request newRequest = request.newBuilder()
                                .removeHeader(AUTH_HEADER_KEY)
                                .addHeader(AUTH_HEADER_KEY, BEARER_HEADER_VALUE + newToken.getAccessToken())
                                .build();

            // return the outcome of the newly signed request
            response = chain.proceed(newRequest);

        }

        return response;
    }
}

期望的解决方案:所有的线程应该等待一个单一的令牌刷新:第一次失败的请求触发刷新,并与其他请求一起等待新的令牌

Desired solution: All threads should wait for one single token refresh: the first failing request triggers the refresh, and together with the other requests waits for the new token.

什么是进行这个好办法? OkHttp的一些内置功能(如身份验证器)可以帮助?谢谢你的任何提示。

What is a good way to proceed about this? Can some built-in features of OkHttp (like the Authenticator) be of help? Thank you for any hint.

推荐答案

谢谢您的回答 - 他们使我的解决方案。我结束了使用 ConditionVariable 锁和的AtomicBoolean。

Thanks for your answers - they led me to the solution. I ended up using a ConditionVariable lock and an AtomicBoolean.

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

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