[英]How to refresh token with Flutter Http Retry Client?
I am storing API request result with Token and refresh token sharedpreferences.我正在使用令牌和刷新令牌共享首选项存储 API 请求结果。 Refresh time is 1 hour.刷新时间为 1 小时。
When the token expires, the token is renewed with RetryClient, but it is not reflected in the application.当令牌过期时,使用 RetryClient 更新令牌,但不会反映在应用程序中。 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.我想要做的是当你给401状态码时,它会自动更新背面的令牌并再次发出请求。
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.当我在状态码为 401 时返回该方法时,我解决了问题。
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) {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.