在OkHttp拦截器中刷新令牌

时间:2016-10-16 08:14:59

标签: android-asynctask okhttp

我正在编写一个拦截器,当我得到401时,我使用刷新令牌在后台获取访问令牌,并在请求中设置新访问令牌。以下是代码:

```@Override         public Response intercept(final Chain chain)抛出IOException {

         Request request = chain.request();
         Response response = chain.proceed(request);
        if (response.code() != 200) {

            try {
                new TokenRequestTask(tokenRequest, request, OkHttpresponse, chain).execute().get(5000, TimeUnit.MILLISECONDS);

                response=chain.proceed(request);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }

        return response;

    }```

在异步任务中在postExecution中,我通过添加收到的新的authtoken来更改请求的标头。但问题是输出不符合预期。该函数返回旧的响应,因为之后异步任务的结果。理想情况下,它应该等待异步任务结果,然后返回但不会发生。怎么做到这一点?

1 个答案:

答案 0 :(得分:3)

我正在另一个线程上使用协议缓冲区获取getRefreshToken并成功完成!这是我的代码:

public class IgapRetrofitInterceptor implements Interceptor {

private boolean isRefreshing;

private TokenContainer tokenContainer = TokenContainer.getInstance();

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

    Request.Builder builder = request.newBuilder();
    builder.header("Authorization", tokenContainer.getToken());
    builder.header("Content-Type", "application/json");
    builder.method(original.method(), original.body());

    String token = tokenContainer.getToken();

    request = builder.build();
    Response response = chain.proceed(request);

    if (response.code() == 401) {
        synchronized (this) {
            Log.e("refreshToken", "Failed " + request.toString() + " with token -> " + tokenContainer.getToken());

            String currentToken = tokenContainer.getToken();

            if (currentToken != null && currentToken.equals(token)) {
                try {
                    getRefreshToken(); //aysnc
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            if (tokenContainer.getToken() != null) {
                builder.header("Authorization", tokenContainer.getToken());
                request = builder.build();
                Log.e("refreshToken", "Send " + request.toString() + " again with new token -> " + tokenContainer.getToken());
                Log.e("refreshToken", "--------------------------------------------------------------------------------");
                return chain.proceed(request);
            }
        }
    }

    Log.i("refreshToken", "req 200 with token -> " + tokenContainer.getToken());

    return response;
}

public synchronized void getRefreshToken() throws InterruptedException {
    if (!isRefreshing) {

        isRefreshing = true;

        Log.e("refreshToken", "Refreshing token...");
        tokenContainer.getRefreshToken(() -> {
            synchronized (IgapRetrofitInterceptor.this) {
                isRefreshing = false;
                Log.e("refreshToken", "Proto response on success and token updated with token -> " + tokenContainer.getToken());
                IgapRetrofitInterceptor.this.notifyAll();
            }
        });
    }

    Log.e("refreshToken", "lock thread -> " + android.os.Process.getThreadPriority(android.os.Process.myTid()) + this.toString());
    this.wait();
    Log.e("refreshToken", "unlock thread -> " + android.os.Process.getThreadPriority(android.os.Process.myTid()) + this.toString());

 }
}