Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 当向服务器发送多个请求时,Okhttp刷新过期令牌_Java_Android_Http_Retrofit_Okhttp - Fatal编程技术网

Java 当向服务器发送多个请求时,Okhttp刷新过期令牌

Java 当向服务器发送多个请求时,Okhttp刷新过期令牌,java,android,http,retrofit,okhttp,Java,Android,Http,Retrofit,Okhttp,我有一个ViewPager,同时加载ViewPager时会调用三个webservice 当第一个返回401时,Authenticator被调用,我刷新了Authenticator中的令牌,但剩余的2个请求已使用旧的刷新令牌发送到服务器,并失败,498被截取到拦截器中,应用被注销 这不是我所期望的理想行为。我希望将第2个和第3个请求保留在队列中,当令牌刷新时,重试排队的请求 目前,我有一个变量来指示在验证器中是否正在进行令牌刷新,在这种情况下,我取消拦截器中的所有后续请求,用户必须手动刷新页面,或

我有一个
ViewPager
,同时加载
ViewPager
时会调用三个webservice

当第一个返回401时,
Authenticator
被调用,我刷新了
Authenticator
中的令牌,但剩余的2个请求已使用旧的刷新令牌发送到服务器,并失败,498被截取到拦截器中,应用被注销

这不是我所期望的理想行为。我希望将第2个和第3个请求保留在队列中,当令牌刷新时,重试排队的请求

目前,我有一个变量来指示在
验证器
中是否正在进行令牌刷新,在这种情况下,我取消
拦截器
中的所有后续请求,用户必须手动刷新页面,或者我可以注销用户并强制用户登录

对于上述问题,使用okhttp 3.x for Android有什么好的解决方案或体系结构

编辑:我想解决的问题是一般性的,我不想给我的电话排序。i、 e.等待一个调用完成并刷新令牌,然后只发送活动和片段级别的其余请求

请求代码。这是
验证器的标准代码

public class CustomAuthenticator implements Authenticator {

    @Inject AccountManager accountManager;
    @Inject @AccountType String accountType;
    @Inject @AuthTokenType String authTokenType;

    @Inject
    public ApiAuthenticator(@ForApplication Context context) {
    }

    @Override
    public Request authenticate(Route route, Response response) throws IOException {

        // Invaidate authToken
        String accessToken = accountManager.peekAuthToken(account, authTokenType);
        if (accessToken != null) {
            accountManager.invalidateAuthToken(accountType, accessToken);
        }
        try {
                // Get new refresh token. This invokes custom AccountAuthenticator which makes a call to get new refresh token.
                accessToken = accountManager.blockingGetAuthToken(account, authTokenType, false);
                if (accessToken != null) {
                    Request.Builder requestBuilder = response.request().newBuilder();

                    // Add headers with new refreshToken

                    return requestBuilder.build();
            } catch (Throwable t) {
                Timber.e(t, t.getLocalizedMessage());
            }
        }
        return null;
    }
}
一些类似的问题: 您可以执行以下操作:

将其添加为数据成员:

// these two static variables serve for the pattern to refresh a token
private final static ConditionVariable LOCK = new ConditionVariable(true);
private static final AtomicBoolean mIsRefreshing = new AtomicBoolean(false);
然后在截取方法上:

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

        // 1. sign this request
        ....

        // 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) {

            if (!TextUtils.isEmpty(token)) {
                /*
                *  Because we send out multiple HTTP requests in parallel, they might all list a 401 at the same time.
                *  Only one of them should refresh the token, because otherwise we'd refresh the same token multiple times
                *  and that is bad. Therefore we have these two static objects, a ConditionVariable and a boolean. The
                *  first thread that gets here closes the ConditionVariable and changes the boolean flag.
                */
                if (mIsRefreshing.compareAndSet(false, true)) {
                    LOCK.close();

                    /* we're the first here. let's refresh this token.
                    *  it looks like our token isn't valid anymore.
                    *  REFRESH the actual token here
                    */

                    LOCK.open();
                    mIsRefreshing.set(false);
                } else {
                    // Another thread is refreshing the token for us, let's wait for it.
                    boolean conditionOpened = LOCK.block(REFRESH_WAIT_TIMEOUT);

                    // If the next check is false, it means that the timeout expired, that is - the refresh
                    // stuff has failed.
                    if (conditionOpened) {

                        // another thread has refreshed this for us! thanks!
                        // sign the request with the new token and proceed
                        // return the outcome of the newly signed request
                        response = chain.proceed(newRequest);
                    }
                }
            }
        }

        // check if still unauthorized (i.e. refresh failed)
        if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            ... // clean your access token and prompt for request again.
        }

        // returning the response to the original request
        return response;
    }

这样,您将只发送一个刷新令牌的请求,然后每隔一次您将拥有刷新的令牌。

您可以尝试使用此应用程序级拦截器

 private class HttpInterceptor implements Interceptor {

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

        //Build new request
        Request.Builder builder = request.newBuilder();
        builder.header("Accept", "application/json"); //if necessary, say to consume JSON

        String token = settings.getAccessToken(); //save token of this request for future
        setAuthHeader(builder, token); //write current token to request

        request = builder.build(); //overwrite old request
        Response response = chain.proceed(request); //perform request, here original request will be executed

        if (response.code() == 401) { //if unauthorized
            synchronized (httpClient) { //perform all 401 in sync blocks, to avoid multiply token updates
                String currentToken = settings.getAccessToken(); //get currently stored token

                if(currentToken != null && currentToken.equals(token)) { //compare current token with token that was stored before, if it was not updated - do update

                    int code = refreshToken() / 100; //refresh token
                    if(code != 2) { //if refresh token failed for some reason
                        if(code == 4) //only if response is 400, 500 might mean that token was not updated
                            logout(); //go to login screen
                        return response; //if token refresh failed - show error to user
                    }
                }

                if(settings.getAccessToken() != null) { //retry requires new auth token,
                    setAuthHeader(builder, settings.getAccessToken()); //set auth token to updated
                    request = builder.build();
                    return chain.proceed(request); //repeat request with new token
                }
            }
        }

        return response;
    }

    private void setAuthHeader(Request.Builder builder, String token) {
        if (token != null) //Add Auth token to each request if authorized
            builder.header("Authorization", String.format("Bearer %s", token));
    }

    private int refreshToken() {
        //Refresh token, synchronously, save it, and return result code
        //you might use retrofit here
    }

    private int logout() {
        //logout your user
    }
}
您可以像这样将拦截器设置为okHttp实例

    Gson gson = new GsonBuilder().create();

    OkHttpClient httpClient = new OkHttpClient();
    httpClient.interceptors().add(new HttpInterceptor());

    final RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(BuildConfig.REST_SERVICE_URL)
            .setClient(new OkClient(httpClient))
            .setConverter(new GsonConverter(gson))
            .setLogLevel(RestAdapter.LogLevel.BASIC)
            .build();

    remoteService = restAdapter.create(RemoteService.class);

希望这有帮助

需要注意的是,
accountManager.blockingGetAuthToken
(或非阻塞版本)仍然可以在侦听器之外的其他地方调用。因此,防止此问题发生的正确位置应在身份验证程序中

我们希望确保需要访问令牌的第一个线程将检索它,其他线程可能只需注册回调,以便在第一个线程完成检索令牌时调用。
好消息是,
AbstractAccountAuthenticator
已经有了一种传递异步结果的方法,即
AccountAuthenticatorResponse
,您可以调用
onResult
onError


以下示例由3个块组成

第一个是确保只有一个线程获取访问令牌,而其他线程只注册它们的
响应
进行回调

第二个部分只是一个虚拟的空结果包。在这里,您将加载您的令牌,可能会刷新它,等等

第三部分是一旦得到结果(或错误)后所做的事情。您必须确保为可能已注册的每个其他线程调用响应

boolean fetchingToken;
List<AccountAuthenticatorResponse> queue = null;

@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {

  synchronized (this) {
    if (fetchingToken) {
      // another thread is already working on it, register for callback
      List<AccountAuthenticatorResponse> q = queue;
      if (q == null) {
        q = new ArrayList<>();
        queue = q;
      }
      q.add(response);
      // we return null, the result will be sent with the `response`
      return null;
    }
    // we have to fetch the token, and return the result other threads
    fetchingToken = true;
  }

  // load access token, refresh with refresh token, whatever
  // ... todo ...
  Bundle result = Bundle.EMPTY;

  // loop to make sure we don't drop any responses
  for ( ; ; ) {
    List<AccountAuthenticatorResponse> q;
    synchronized (this) {
      // get list with responses waiting for result
      q = queue;
      if (q == null) {
        fetchingToken = false;
        // we're done, nobody is waiting for a response, return
        return null;
      }
      queue = null;
    }

    // inform other threads about the result
    for (AccountAuthenticatorResponse r : q) {
      r.onResult(result); // return result
    }

    // repeat for the case another thread registered for callback
    // while we were busy calling others
  }
}
boolean-fetchingToken;

列表,其中详细介绍了并发性。如果您对RxJava如何在引擎盖下工作感兴趣,那么这个博客是一个很好的来源。

我找到了一个带有验证器的解决方案,id是请求的编号,仅用于识别。评论用西班牙语

 private final static Lock locks = new ReentrantLock();

httpClient.authenticator(new Authenticator() {
            @Override
            public Request authenticate(@NonNull Route route,@NonNull Response response) throws IOException {

                Log.e("Error" , "Se encontro un 401 no autorizado y soy el numero : " + id);

                //Obteniendo token de DB
                SharedPreferences prefs = mContext.getSharedPreferences(
                        BuildConfig.APPLICATION_ID, Context.MODE_PRIVATE);

                String token_db = prefs.getString("refresh_token","");

                //Comparando tokens
                if(mToken.getRefreshToken().equals(token_db)){

                    locks.lock(); 

                    try{
                        //Obteniendo token de DB
                         prefs = mContext.getSharedPreferences(
                                BuildConfig.APPLICATION_ID, Context.MODE_PRIVATE);

                        String token_db2 = prefs.getString("refresh_token","");
                        //Comparando tokens
                        if(mToken.getRefreshToken().equals(token_db2)){

                            //Refresh token
                            APIClient tokenClient = createService(APIClient.class);
                            Call<AccessToken> call = tokenClient.getRefreshAccessToken(API_OAUTH_CLIENTID,API_OAUTH_CLIENTSECRET, "refresh_token", mToken.getRefreshToken());
                            retrofit2.Response<AccessToken> res = call.execute();
                            AccessToken newToken = res.body();
                            // do we have an access token to refresh?
                            if(newToken!=null && res.isSuccessful()){
                                String refreshToken = newToken.getRefreshToken();

                                    Log.e("Entra", "Token actualizado y soy el numero :  " + id + " : " + refreshToken);

                                    prefs = mContext.getSharedPreferences(BuildConfig.APPLICATION_ID, Context.MODE_PRIVATE);
                                    prefs.edit().putBoolean("log_in", true).apply();
                                    prefs.edit().putString("access_token", newToken.getAccessToken()).apply();
                                    prefs.edit().putString("refresh_token", refreshToken).apply();
                                    prefs.edit().putString("token_type", newToken.getTokenType()).apply();

                                    locks.unlock();

                                    return response.request().newBuilder()
                                            .header("Authorization", newToken.getTokenType() + " " + newToken.getAccessToken())
                                            .build();

                             }else{
                                //Dirigir a login
                                Log.e("redirigir", "DIRIGIENDO LOGOUT");

                                locks.unlock();
                                return null;
                            }

                        }else{
                            //Ya se actualizo tokens

                            Log.e("Entra", "El token se actualizo anteriormente, y soy el no : " + id );

                            prefs = mContext.getSharedPreferences(BuildConfig.APPLICATION_ID, Context.MODE_PRIVATE);

                            String type = prefs.getString("token_type","");
                            String access = prefs.getString("access_token","");

                            locks.unlock();

                            return response.request().newBuilder()
                                    .header("Authorization", type + " " + access)
                                    .build();
                        }

                    }catch (Exception e){
                        locks.unlock();
                        e.printStackTrace();
                        return null;
                    }


                }
                return null;
            }
        });
private final static locks=new ReentrantLock();
httpClient.authenticator(新的authenticator(){
@凌驾
公共请求身份验证(@NonNull路由,@NonNull响应)引发IOException{
Log.e(“错误”,“Se encontro un 401无自动调整和编号:+id”);
//Obteniendo代币de DB
SharedReferences prefs=mContext.getSharedReferences(
BuildConfig.APPLICATION\u ID,Context.MODE\u PRIVATE);
String-token\u-db=prefs.getString(“刷新\u-token”,”);
//比兰多代币
if(mToken.getRefreshToken().equals(token_db)){
locks.lock();
试一试{
//Obteniendo代币de DB
prefs=mContext.getSharedReferences(
BuildConfig.APPLICATION\u ID,Context.MODE\u PRIVATE);
String token_db2=prefs.getString(“refresh_token”,”);
//比兰多代币
if(mToken.getRefreshToken().equals(token_db2)){
//刷新令牌
APIClient tokenClient=createService(APIClient.class);
Call Call=tokenClient.getRefreshAccessToken(API_OAUTH_CLIENTID,API_OAUTH_CLIENTSECRET,“refresh_token”,mToken.getRefreshToken());
Response res=call.execute();
AccessToken newToken=res.body();
//我们是否有要刷新的访问令牌?
if(newToken!=null&&res.issusccessful()){
字符串refreshToken=newToken.getRefreshToken();
Log.e(“Entra”、“Token-actualizado y-soy-el-numero:“+id+”:“+refreshttoken”);
prefs=mContext.getSharedReferences(BuildConfig.APPLICATION\u ID,Context.MODE\u PRIVATE);
prefs.edit().putBoolean(“登录”,true.apply();
prefs.edit().putString(“访问令牌”,newToken.getAccessToken()).apply();
prefs.edit().putString(“刷新令牌”,刷新令牌).apply();
prefs.edit().putString(“token_type”,newToken.getTokenType()).apply();
locks.unlock();
返回response.request().newBuilder()
.header(“授权