I am trying to recall the API request after getting the refresh token from the API. Having issue in recall the same API request. It shows invalid access token error while running this api. how to fix this issue.
How to recall the get API request to get the access token .
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;
}
How to fix this issue? Help me with the solution.