OkHttp异步拦截器或验证器

时间:2015-08-25 20:24:06

标签: okhttp

有没有办法拦截或验证请求异步?例如在这样的流程中:从用户获取密码,使用它来获取令牌然后重试被拦截的呼叫?

1 个答案:

答案 0 :(得分:1)

我遇到同样的问题here

我在代码中的getToken方法中使用了wait()notify(),但是因为我在Retrofit库中使用了OkHttp,所以它创建了一个新线程并且可以在这里进行异步操作。 / p>

    public synchronized void getToken() throws InterruptedException {
    if (!isRefreshing()) {
        //This is very important to call notify() on the same object that we call wait();
        final TokenProvider myInstance = this;
        setRefreshing(true);
        Log.d("refreshToken", "Refreshing token..." );

       //Make async call
       getRestClient().getAccountService().getRefreshedToken(mLoginData.getRefreshToken())
                .subscribe(new Observer<LoginResponse>() {
                    @Override
                    public void onCompleted() {
                        synchronized (myInstance) {
                            setRefreshing(false);
                            Log.d("refreshToken", "notifyAll onComplete.");
                            myInstance.notifyAll();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        synchronized (myInstance) {
                            setRefreshing(false);
                            myInstance.notifyAll();
                            Log.d("refreshToken", "onError .");
                        }
                    }

                    @Override
                    public void onNext(LoginResponse loginResponse) {
                        synchronized (myInstance) {
                            mLoginData = loginResponse;
                            Log.d("refreshToken", "notifyAll onNext .");
                            myInstance.notifyAll();
                        }
                    }
                });
    }

        Log.d("refreshToken", "before wait ." + android.os.Process.getThreadPriority(android.os.Process.myTid()) + this.toString());
        this.wait();
        Log.d("refreshToken", "after wait ." + android.os.Process.getThreadPriority(android.os.Process.myTid()) + this.toString());
}

您可以尝试这是否适合您。