flutter 如何在调用refreshtoken api后重试api请求?

pepwfjgg  于 2022-11-30  发布在  Flutter
关注(0)|答案(1)|浏览(214)

你好,我在dart中使用http拦截器来处理refreshtoken,一旦使用拦截器调用了refreshtoken api并获得了新的访问权限,我如何再次调用api请求?

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(),
);
r3i60tvu

r3i60tvu1#

基本上你需要错误401(未授权)并不一定意味着令牌已经过期,所以我相信你应该有一个刷新令牌来处理这种情况。如果你的API有一个刷新令牌,那么这样做。

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;
    }
   }

相关问题