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.
Remove last return response; and unnecessary Future.delayed. Something like this could work:
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');
}
}
Related
My post request doesn't work
I've tried running this but i end up with :
{"requestError":{"serviceException":{"messageId":"UNAUTHORIZED","text":"Invalid logindetails"}}}
This is my code :
data() async {
final client = HttpClient();
final request = await client .postUrl(Uri.parse("https://....api.infobip.com/sms/2/text/advanced")); request.headers.set(HttpHeaders.contentTypeHeader, "{'Authorization':'App ...KEY','Content-Type': 'application/json','Accept': 'application/json'}");
request.write({ '"messages": [{"from": "sms","destinations": [{"to": "..."}],"text": "ABC"}]' });
final response = await request.close();
response.transform(utf8.decoder).listen((contents) {
print(contents);
});
}
I just figured out an answer for this POST request in flutter
makePostRequest(int number) async {
final uri = Uri.parse('https://....api.infobip.com/sms/2/text/advanced');
final headers = {
'Authorization':
'App API-KEY',
'Content-Type': 'application/json'
};
Map<String, dynamic> body = {
"messages": [
{
"from": "SenderID",
"destinations": [
{"to": number}
],
"text": "TEST!"
}
]
};
String jsonBody = json.encode(body);
final encoding = Encoding.getByName('utf-8');
Response response = await post(
uri,
headers: headers,
body: jsonBody,
encoding: encoding,
);
int statusCode = response.statusCode;
String responseBody = response.body;
print(responseBody);
}
I want to print data from the api but i am getting this error below:
DioError [DioErrorType.response]: Http status error [500]
Check the screenshot below from postman, It is working well.
Below is my code, I need help. I get error when I call this function below:
Future<void> signInData([data]) async {
final prefs = await SharedPreferences.getInstance();
final String token = prefs.getString('token') ?? "";
try {
Response response = await _dio.post('$_baseUrl/api/gateway',
data: {
{
"ClientPackageId": "0cdd231a-d7ad-4a68-a934-d373affb5100",
"PlatformId": "ios",
"ClientUserId": "AhmedOmar",
"VinNumber": VINumber
}
},
options: Options(headers: {
"Content-Type": "application/json",
"Authorization": "Bearer $token",
}));
print(response.data);
print(response.statusCode);
if (response.statusCode == 401) {
// call your refresh token api here and save it in shared preference
await getToken();
signInData(data);
}
} catch (e) {
print(e);
}
}
Hey remove extra { from data inside post method like below -
Future<void> signInData([data]) async {
final prefs = await SharedPreferences.getInstance();
final String token = prefs.getString('token') ?? "";
try {
Response response = await _dio.post('$_baseUrl/api/gateway',
data: {
"ClientPackageId": "0cdd231a-d7ad-4a68-a934-d373affb5100",
"PlatformId": "ios",
"ClientUserId": "AhmedOmar",
"VinNumber": VINumber
},
options: Options(headers: {
"Content-Type": "application/json",
"Authorization": "Bearer $token",
}));
print(response.data.toString());
print(response.statusCode);
if (response.statusCode == 401) {
// call your refresh token api here and save it in shared preference
await getToken();
signInData(data);
}
} catch (e) {
print(e);
}
}
Using NextJS 12 and axios to try to get and set a cookie in the interceptor on the server side with no luck. Does anyone know how to get/set cookie in this instance?
const axiosApiInstance = axios.create({ withCredentials: true });
axiosApiInstance.interceptors.request.use(
async config => {
config.headers = {
'Authorization': `Bearer ${config.headers.cookie}`,
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}
config.withCredentials = true;
return config;
},
error => {
Promise.reject(error);
}
);
axiosApiInstance.interceptors.response.use((response) => {
response.headers.cookie = cookie.serialize(
"token",
"hello world"
)
return response;
}, async function(error) {
return Promise.reject(error);
}
);
Is there someway I can pass the cookie as an argument to the interceptor?
const response = await axiosApiInstance.post(cookie??, url, data, { headers: cookie?? }}
I often use Axios to perform requests in my applications, however due to incompatibility with iphone, I had to use the capacitor-community/http library, however the try catch blocks are always returning success, even if there was an error in the request. How can I handle errors using this library?
try {
await Requester.auth.public.login(formData);
this.$store.dispatch('login', user);
this.$root.$emit('showToast', {
text: 'Seja bem vindo!',
color: 'success',
});
this.$router.push({ name: 'Cotacao' });
} catch (err) {
this.$root.$emit('showToast', {
text: err.response?.data ?? err.toString(),
color: 'error',
});
} finally {
this.loading.submitForm = false;
}
},
My request
const login = async (formData: AuthLoginFormData): Promise<User> => {
const res: HttpResponse = await Http.post({
url: `${BASE_URL}public/auth/login`,
headers: {
'Content-Type': 'application/json',
},
data: formData,
webFetchExtra: {
credentials: 'include',
},
});
return res.data;
};
Install Latest https://github.com/capacitor-community/http plugin
use function
public async login(formData: AuthLoginFormData){
let options = {
url: `${BASE_URL}public/auth/login`,
headers: {
'Content-Type': 'application/json',
},
data: formData,
webFetchExtra: {
credentials: 'include',
}
};
let response: HttpResponse = await Http.request(options);
if (response.status === 200) {
return Promise.resolve(res);
}
return Promise.reject(response.data);
}
I have a POST request:
static String url = 'https://checkout.test.paycom.com/api';
static Map<String, String> headers = {
'Host': 'checkout.test.paycom.com',
'X-Auth': '1234',
'Cache-Control': 'no-cache'
};
Future<Map<String, dynamic>> createCard() async {
try {
Map<String, dynamic> body = {
"id": '123',
"method": "receipts.create",
"params": {
"amount": '2500',
"account": {"order_id": '106'}
}
}
final response = await http.post(url, body: body, headers: headers);
print(response.body);
} catch (e) {
print(e.toString());
}
return null;
}
and give an error
type '_InternalLinkedHashMap<String, Object>' is not a subtype of type 'String' in type cast
What I am doing wrong?
your body needs to be as string, best case for you could be convert your body as JSON String as below:
final response = await http.post(url, body: jsonEncode(body), headers: headers);