即使没有401也会调用OkHttp3 Authenticator

时间:2019-01-09 06:43:38

标签: android okhttp3

我有一个身份验证器,我认为仅在有401个api调用时才应触发。但是我面临一个奇怪的行为,由于某种原因,即使没有401也会调用authenticate()方法。

然后,该应用程序进入多次刷新令牌的循环。我确信authenticate()是刷新刷新的访问令牌的唯一位置。

这是我的Authenticator类的外观:

  public class MyAuthenticator implements Authenticator {

  Context context;

  public MyAuthenticator(Context context) {
     this.context = context;
  }

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

    Retrofit client = new Retrofit.Builder()
        .baseUrl(URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

    ApiService service = client.create(ApiService.class);

    SharedPreferenceManager sharedPreferenceManager = new 
    SharedPreferenceManager(context);
    String refreshToken = 
    sharedPreferenceManager.getRefreshToken(context);

    AuthRequest authRequest = new AuthRequest();
    authRequest.grant_type = "refresh_token";
    authRequest.refresh_token = refreshToken;

    Call<authResponse> refreshTokenResult = 
    service.refreshToken(authRequest);
    retrofit2.Response accessTokenResponse = 
    refreshTokenResult.execute();
    //check if response equals 400 , mean empty response
    if (accessTokenResponse.isSuccessful()) {
        AuthResponse refreshResult  = (AuthResponse) 
        accessTokenResponse.body();

        //save new access and refresh token
        sharedPreferenceManager.writeLoginResponse(context, 
        refreshResult);
       // then create a new request and modify it accordingly using the 
        new token
       return response.request().newBuilder()
            .header("Authorization", "Bearer " + 
       refreshResult.access_token)
            .build();

   } else {

     Login_.intent(context).flags(Intent.FLAG_ACTIVITY_NEW_TASK 
     | Intent.FLAG_ACTIVITY_CLEAR_TASK).start();
       return null;

   }
  }
 }

我是否需要在收到401的authenticate()方法中进行显式检查? 互联网连接不稳定时,似乎会发生这种情况。

0 个答案:

没有答案