I am storing API request result with Token and refresh token sharedpreferences. Refresh time is 1 hour.
When the token expires, the token is renewed with RetryClient, but it is not reflected in the application. This process only happens when you refresh the page. Where am I doing wrong? What I want to do is when you give the 401 status code, it will automatically renew the token on the back and make a request again.
Future<HttpResult> post(url,
{Map<String, String>? headers, String? body}) async {
final client = RetryClient(Client(), retries: 1, when: (response) {
return response.statusCode == 401 ? true : false;
}, onRetry: (req, res, retryCount) async {
await refreshToken(); //
});
try {
final response = await client.post(url, headers: headers, body: body);
return HttpResult(data: response.body, status: _setStatus(response));
} catch(e) {
}
}
Future addFood(Food food) async {
try {
final token = SharedManager.instance.getStringValue(SharedKeys.TOKEN);
Uri endpoint =
Uri.https(AppConstant.apiServiceUrl, 'foods.json', {"auth": token});
final jsonModel = jsonEncode(food.toJson());
final request = await httpClient.post(endpoint, body: jsonModel);
if (request.status == Status.success) {;
return "Success";
}
return "Don't.";
} catch (e) {}
When I returned that method when the Status Code was 401, I solved the problem.
Future addFood(Food food) async {
try {
final token = SharedManager.instance.getStringValue(SharedKeys.TOKEN);
Uri endpoint =
Uri.https(AppConstant.apiServiceUrl, 'foods.json', {"auth": token});
final jsonModel = jsonEncode(food.toJson());
final request = await httpClient.post(endpoint, body: jsonModel);
if (request.status == Status.success) { //enum -> success (200)
return "Success";
}if (result.status == Status.unauthorized) { //enum -> unauthrozied (401)
return addFood(food);
}
return "Don't.";
} catch (e) {}
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.