http_interceptor icon indicating copy to clipboard operation
http_interceptor copied to clipboard

headers are not getting updated upon retry

Open santosh81066 opened this issue 3 years ago • 12 comments

when I am trying to retry a request headers are not getting updated following is my interceptor

class AuthorizationInterceptor extends InterceptorContract {
  @override
  Future<BaseRequest> interceptRequest({required BaseRequest request}) async {
    final prefs = await SharedPreferences.getInstance();

    final extractData =
        json.decode(prefs.getString('userData')!) as Map<String, dynamic>;
    request.headers.clear();
    request.headers['Authorization'] = await extractData['accessToken'];
    print(
        'this is from AuthorizationInterceptor: ${extractData['accessToken']}');
    // TODO: implement interceptRequest

    return request;
  }



}

santosh81066 avatar Aug 28 '22 05:08 santosh81066

If you are using prereleases of v2.0.0+beta.1 or above, then the API has changed a bit. Check out the guides for 2.0.0 if you want to know how much has changed.

In any case, here's an example of how to set headers with the new API:

class WeatherApiInterceptor extends InterceptorContract {
  @override
  Future<BaseRequest> interceptRequest({required BaseRequest request}) async {
    final cache = await SharedPreferences.getInstance();

    final Map<String, String>? headers = Map.from(request.headers);
    headers?[HttpHeaders.contentTypeHeader] = "application/json";

    return request.copyWith(
      url: request.url.addParameters({
        'appid': cache.getString(kOWApiToken) ?? '',
        'units': 'metric',
      }),
      headers: headers,
    );
  }

  @override
  Future<BaseResponse> interceptResponse(
          {required BaseResponse response}) async =>
      response;
}

CodingAleCR avatar Aug 28 '22 05:08 CodingAleCR

Also, thank you for opening an issue, I appreciate you reaching out! 😄

CodingAleCR avatar Aug 28 '22 05:08 CodingAleCR

hello sir thx for quick reply as you sujested I had changed my interceptor but the result is same Screenshot 2022-08-28 at 12 36 57 you can see in the image that the access token which I am printing and accesstoken which I am refreshing using refresh token is same but headers not updating

class AuthorizationInterceptor extends InterceptorContract {
  @override
  Future<BaseRequest> interceptRequest({required BaseRequest request}) async {
    final prefs = await SharedPreferences.getInstance();

    final extractData =
        json.decode(prefs.getString('userData')!) as Map<String, dynamic>;

    final Map<String, String> headers = Map.from(request.headers);
    headers['Authorization'] = await extractData['accessToken'];
    print(
        'this is from AuthorizationInterceptor: ${extractData['accessToken']}');
    // TODO: implement interceptRequest

    return request.copyWith(
      headers: headers,
    );
  }

santosh81066 avatar Aug 28 '22 07:08 santosh81066

Taking a closer look to your retry policy (the one sent via email) I've noticed one thing: you are not returning true when you are refreshing your token.

class ExpiredTokenRetryPolicy extends RetryPolicy {
  BuildContext context;
  ExpiredTokenRetryPolicy(this.context);
  @override

  int get maxRetryAttempts => 2;

  @override
  Future<bool> shouldAttemptRetryOnResponse(BaseResponse response) async {
    if (response.statusCode == 401) {
      print('retry token started');
  

      await Provider.of<Auth>(context, listen: false).restoreAccessToken();
    }
    return false;
  }
}

This is needed because otherwise the RetryPolicy will not know when to perform retries on response, and thus the requests will still use the 'old' token. Here's the example ExpiredTokenRetryPolicy from the WeatherApp provided with the library:

class ExpiredTokenRetryPolicy extends RetryPolicy {
  @override
  int get maxRetryAttempts => 2;

  @override
  Future<bool> shouldAttemptRetryOnException(
    Exception reason,
    BaseRequest request,
  ) async {
    log(reason.toString());

    return false;
  }

  @override
  Future<bool> shouldAttemptRetryOnResponse(BaseResponse response) async {
    if (response.statusCode == 401) {
      log('Retrying request...');
      final cache = await SharedPreferences.getInstance();

      cache.setString(kOWApiToken, kOpenWeatherApiKey);

      // Notice how in here the policy returns true so that the library can now
      // when to perform a retry. In this case it is when the response's status
      // code is 401 Unauthorized.
      return true;
    }

    return false;
  }
}

CodingAleCR avatar Aug 29 '22 05:08 CodingAleCR

hello sir as you said I had kept return true but I am facing exception if I get 401 response Screenshot 2022-08-29 at 12 27 34

santosh81066 avatar Aug 29 '22 07:08 santosh81066

This seems like a bug in the beta version. I think it was mentioned in an issue before. Will take a look and get back to you 👀

CodingAleCR avatar Aug 29 '22 07:08 CodingAleCR

By any chance are you using a MultipartRequest to upload a file (e.g. upload profile picture to a server)?

CodingAleCR avatar Aug 29 '22 07:08 CodingAleCR

yeah

santosh81066 avatar Aug 29 '22 07:08 santosh81066

This seems like a bug in the beta version. I think it was mentioned in an issue before. Will take a look and get back to you 👀

thank you waiting for update

santosh81066 avatar Aug 29 '22 07:08 santosh81066

hello sir may I know approximate next release date

santosh81066 avatar Aug 30 '22 11:08 santosh81066

Hey, yes, hum in terms of ETA I can't give you one, but I can confirm at the moment that it is a bug. I'm working to fix this but it might need a big refactor.

CodingAleCR avatar Sep 02 '22 15:09 CodingAleCR

ok thank you

santosh81066 avatar Sep 02 '22 16:09 santosh81066

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Nov 12 '22 05:11 stale[bot]