简体   繁体   中英

How to retry api request once the refreshtoken api is called?

Hi im using http interceptor in dart to handle refreshtoken, How can i call the api request again once the refreshtoken api is called in using thee interceptor and got the new accesstoken.

   class ExpiredTokenRetryPolicy extends RetryPolicy {
   @override
   Future<bool> shouldAttemptRetryOnResponse(ResponseData response) async {
   if (response.statusCode == 401) {
   await GetFitbitAccessToken().getAccessToken();
   return true;
    }

   return false;
    }
   }


              ------------------------------------

Client client = InterceptedClient.build(
interceptors: [
  FitbitApiInterceptor(),
 ],

 retryPolicy: ExpiredTokenRetryPolicy(),
);

Basically you need error 401(UnAuthorized) does not necessarily mean the token has expired so I believe you should have a refresh token to handle such cases. If your API has a refresh token then do this.

class ExpiredTokenRetryPolicy extends RetryPolicy {
   @override
   Future<bool> shouldAttemptRetryOnResponse(ResponseData response) async {
   if (response.statusCode == 200) {
  // do your normal request
   return true;
    }else if(response.statusCode =401){
     //for POST
    ///within the header add this
     headers: {'grant_type': 'refresh_token', 'refresh_token': 
      '$refresh_token'});
      token = jsonDecode(response.body)['token'];
      refresh_token = jsonDecode(response.body)['refresh_token'];
      return true;
   }

   return false;
    }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM