http icon indicating copy to clipboard operation
http copied to clipboard

client is not waiting to complete my process

Open santosh81066 opened this issue 1 year ago • 3 comments

hello sir actually I am using http client to retry request upon 401 request but on retry I am running another method to restore access token upon completion of my restore process then I want to retry api but before completion my api Is calling again following is my restoreAcessToken.dart

Future<void> restoreAccessToken() async {
    print('restoreAccessToken started');
    final url = '${Ninecabsapi().urlHost}${Ninecabsapi().login}/$sessionId';

    var response = await http.patch(
      Uri.parse(url),
      headers: {
        'Content-Type': 'application/json; charset=UTF-8',
        'Authorization': accessToken!
      },
      body: json.encode(
        {"refresh_token": refreshtoken},
      ),
    );
    var userDetails = json.decode(response.body);

    if (response.statusCode == 401) {
      print(userDetails['messages']);
    }

    sessionId = userDetails['data']['session_id'];
    accessToken = userDetails['data']['access_token'];
    accessTokenExpiryDate = DateTime.now().add(
      Duration(seconds: userDetails['data']['access_token_expiry']),
    );
    refreshToken = userDetails['data']['refresh_token'];
    refreshTokenExpiryDate = DateTime.now().add(
      Duration(seconds: userDetails['data']['refresh_token_expiry']),
    );
    final userData = json.encode({
      'sessionId': sessionId,
      'refreshToken': refreshToken,
      'refreshExpiry': refreshTokenExpiryDate!.toIso8601String(),
      'accessToken': accessToken,
      'accessTokenExpiry': accessTokenExpiryDate!.toIso8601String()
    });
   
    print("this is from restoreAcessToken :$userDetails");
    notifyListeners();
    final prefs = await SharedPreferences.getInstance();

    prefs.setString('userData', userData);
    reset();
  }

following is my api calling function where I want to retry upon response

Future<void> postVehicles(BuildContext context, String vehicleType) async {
    //print(token);

    var data = {"vehicletype": vehicleType, "filename": vehicleType};
    Map<String, String> obj = {"attributes": json.encode(data).toString()};

    var flutterFunctions =
        Provider.of<FlutterFunctions>(context, listen: false);
    final url = Ninecabsapi().urlHost + Ninecabsapi().getvehicle;
    try {
      loading();
      var response = http.MultipartRequest("POST", Uri.parse(url))
        ..files.add(await http.MultipartFile.fromPath(
            "imagefile", flutterFunctions.imageFile!.path,
            contentType: MediaType("image", "jpg")))
        //..headers['Authorization'] = token!
        ..fields.addAll(obj);
      final client = RetryClient(
        http.Client(),
        retries: 1,
        when: (response) {
          return response.statusCode == 401 ? true : false;
        },
        onRetry: (req, res, retryCount) async {
          //print('retry started $token');
          if (retryCount == 0 && res?.statusCode == 401) {
            // Only this block can run (once) until done
            Provider.of<Auth>(context, listen: false).restoreAccessToken();
            req.headers['Authorization'] = token!;

            print('retry started ${req.headers['Authorization']}');
            //req.headers.clear();

          }
        },
      );
      final send = await client.send(response);
      final res = await http.Response.fromStream(send);

      var messages = json.decode(res.body);
      print("this is from postvehicles $messages");

      loading();

      notifyListeners();
    } catch (e) {
      print(e);
    }
  }

santosh81066 avatar Sep 02 '22 05:09 santosh81066

I have the same issue

void main() async {
  final uri = Uri.parse('https://jsonplaceholder.typicode.com/users/1');
  final response = await http.Client().get(uri);
  print(response);
}

Run as console app, the response has been printed, but the main does not exit

hoc081098 avatar Sep 02 '22 08:09 hoc081098

I have the same issue

void main() async {
  final uri = Uri.parse('https://jsonplaceholder.typicode.com/users/1');
  final response = await http.Client().get(uri);
  print(response);
}

Run as console app, the response has been printed, but the main does not exit

hmm

santosh81066 avatar Sep 02 '22 09:09 santosh81066

solved by updating package

santosh81066 avatar Sep 08 '22 15:09 santosh81066