如何在获得刷新令牌后召回API请求?



我试图从API获得刷新令牌后召回API请求。在召回相同API请求时出现问题。在运行此api时显示无效的访问令牌错误。如何解决这个问题。

如何收回get API请求以获取访问令牌

Future<http.Response> _getAPIById(String pathURL) async {
try {
final Uri uri = Uri.http(ApiConstants.baseUrl, pathURL);
print(uri);
print(accessToken);
http.Response response = await _ioClient.get(
uri,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken!
},
);
if (response.statusCode != 200) {
print("Status Not Ok");
print(response.body);
if (response.statusCode == 401) {
await  refreshAccessToken();
print("Status code 401 called");
Future.delayed(
Duration(milliseconds: 1000),
() async {
return await _ioClient.get(
uri,
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
'x-access-token': 'Bearer ' + accessToken!
},
);
});
}
} else if (response.statusCode == 200) {
print("Ok");
print(response.body);
return response;
}
print(response.body);
return response;
} catch (e) {
print(e);
throw Exception('Error occurred');
}
}



Future<String>  refreshAccessToken() async {
Map<String, String> requestBody = {'refresh_token': refreshToken!};
final response = await http.post(
Uri.parse(
ApiConstants.baseUrlWithHttp + ApiConstants.refreshAccessToken),
body: requestBody,
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
encoding: Encoding.getByName("utf-8"));
print("refreshAccessToken");
print(response.body);
if (response.statusCode == 200) {
status = true;
var decodedData = jsonDecode(response.body);
accessToken = decodedData['accessToken'];
refreshToken = decodedData['refreshToken'];
}
return response.body;
}

如何解决这个问题?帮我解决这个问题。

删除最后一个return response;和不需要的Future.delayed。可以这样做:

Future<http.Response> _getAPIById(String pathURL) async {
try {
http.Response response = await _ioClient.get(
Uri.http(ApiConstants.baseUrl, pathURL),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken!
},
);
if (response.statusCode == 401) {
await  refreshAccessToken();
return await _ioClient.get(
uri,
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
'x-access-token': 'Bearer ' + accessToken!
},
);
} else {
return response;
}
} catch (e) {
throw Exception('Error occurred');
}
}

相关内容

  • 没有找到相关文章

最新更新