Future Call return API key invalid error UNAUTHORIZED - flutter

I'm trying to access an api endpoint using a Future and it constantly returns
{"code":"UNAUTHORIZED","message":"Invalid API Key","timestamp":"2022-03-19T16:57:02.300792Z","trackingId":"4E98D1A6:9539_0A5D03B2:01BB_62360B5E_7DAF37:3959"}
I know the reason why it failed is obvious in the error message but I don't know where where my call is going wrong.
I'm using the correct API key
Future<void> getThingsToDo() async {
var headers = {
'exp-api-key': '*******-**My-API*-*KEY-************',
'Accept-Language': 'en-US',
'Accept': 'application/json;version=2.0',
};
try {
var url = Uri.parse(
'https://api.sandbox.viator.com/partner/products/5010SYDNEY');
var response = await http.get(url, headers: headers);
if (response.statusCode == 200) {
var jsonData = json.decode(response.body);
print('Call Worked');
return jsonData;
} else {
print(response.statusCode);
print(response.body);
}
} catch (e) {
print(e);
}
throw Exception(' There is something wrong');
}
These are the sample instructions

Foe anyone using the Viatour api unless you are a merchant don't use the sandbox version.
var url = Uri.parse(
'https://api.sandbox.viator.com/partner/products/5010SYDNEY');
to
var url = Uri.parse(
'https://api.viator.com/partner/products/5010SYDNEY');

Related

Flutter http post request gives status code 401

I am using API to verify phone number provided by user.... on postman api give perfect response and give OTP code in response but in flutter status code 401 is returned
here is my code
Future verifyPhone(String phoneNumber) async {
try {
String token = "528724967b62c6c9e546aeaee1b57e234991ad98";
var body = <String, String>{};
body['user_number'] = phoneNumber;
var url = Uri.parse(ApiKeys.phoneVerifyApiKey);
var response = await http.post(
url,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"authentication": "Bearer $token"
},
body: body,
);
if (response.statusCode == 200) {
print("Code sent");
} else {
print("Failed to send code");
print(response.statusCode);
}
} catch (err) {
print(err.toString());
}
notifyListeners();
}
instead of "code sent" i get "failed to send code" and status code 401
EDIT
You can send form request this way
Future verifyPhone(String phoneNumber) async {
try {
String token = "528724967b62c6c9e546aeaee1b57e234991ad98";
var body = <String, String>{};
body['user_number'] = phoneNumber;
var url = Uri.parse(ApiKeys.phoneVerifyApiKey);
var headers ={
"Content-Type": "application/x-www-form-urlencoded",
"authentication": "Bearer $token"
};
var request = http.MultipartRequest('POST', url)
..headers.addAll(headers)
..fields.addAll(body);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print("Code sent");
} else {
print("Failed to send code");
print(response.statusCode);
}
} catch (err) {
print(err.toString());
}
notifyListeners();
}
EDIT
To access :
var _data = jsonDecode(response);
var list = _data["data"];
print(list[0]['otp_code']);

Flutter - Server Not Seeing UserAgent in Get Request

I am sending get requests in a flutter app and my server is sending a response depending on data from the phones user agent, when i send a request from a native app there is no problem -
example: "Dalvik/2.1.0 (Linux; U; Android 10; Infinix X655C Build/QP1A.190711.020)"
but when i do the same from my flutter app on an android phone the sever sees something else.
example: "Dart/2.16 (dart:io)"
this is happening even though the get request has the headers property in the request
this is the flutter code:
Future<bool> approvedData() async {
var serverUrl = "https://appsofksenia.com/app_data";
String userAgent = await FlutterUserAgent.getPropertyAsync('userAgent');
Map<String, String> headers = {
HttpHeaders.authorizationHeader: 'Basic $userAgent',
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json',
"User-Agent": userAgent,
};
http.Response res = await http.get(Uri.parse(serverUrl),headers: headers);
if(res.statusCode == 200){
if(res.body.isNotEmpty) {
dynamic response = json.decode(res.body);
var serverResponse = PrivacyResponse.fromJson(response);
var serverAnswer = serverResponse.privacy;
if (serverAnswer == "data_change") {
return true;
} else {
return false;
}
}else{
return false;
}
}else{
return false;
}
}
debug of the flutter app
I solved it by using the fk_user_agent library: https://pub.dev/packages/fk_user_agent
You can make a method like this:
Future<String> getUserAgent() async {
try {
await FkUserAgent.init();
var platformVersion = FkUserAgent.userAgent!;
return platformVersion;
} on PlatformException {
return "";
}
}
Then send the return value with the key "user-agent" in the headers Map.

Flutter How to send Http (post) Request using WorkManager Plugin

Hello Guys any help will be apprecited please,
I am unable to send Http post or get request using workmanager plugin in flutter, any solutions to this would be highly appreciated, thanks
Here is my code
any help will be appreciated
thanks
Workmanager.executeTask((task, inputData) async {
switch (task) {
case fetchBackground:
print('checkStatusnow');
final sharedPref = await SharedPreferences.getInstance();
pendingStat = sharedPref.getBool('pendingStat');
print('pendingStat $pendingStat');
// await initialStat();
String url = 'https://getStat.com/chargeStat';
try {
var param = {
'authorization_code': authoStatCode,
'email': umail,
'amount': StatFare *100,
};
String body= json.encode(param);
var response = await http.Client().post(Uri.parse(url), headers: <String, String>{
'Authorization': StatKey,
'Content-Type': 'application/json',
'Accept': 'application/json'
},body: body,
);
if (response.statusCode == 200) {
print(response.body);
print("Successfull");
final data = jsonDecode(response.body);
print(data);
if (StatFounds == null) {
print("Status Not found");
}
else {
print ('checkForSta');
}
}
else {
print(response.reasonPhrase);
print("not available");
sharedPref.setBool("Stat", true);
}
} catch (e) {
}

Flutter - Before .then is executed, Function is returning the value and after that reading .then

I am facing 2 problems with the below code and I think both are related.
createFunction is showing an error -
"This function has a return type of 'FutureOr< bool >', but doesn't end with a return statement. Try adding a return statement, or changing the return type to 'void'." - I need to return true or false, so I have to use return type bool.
When the function is executed, it runs smoothly till the PROBLEM AREA (marked in the code). Here it returns null and then comes back to execute .then . I need to run .then right after http.post is executed. At the end of the code it should return true / false.
Any help will be highly appreciated.
Future<bool> createFunction(image) async {
var request = new http.MultipartRequest("POST", Uri.parse(_urlImage));
request.files.add(
await http.MultipartFile.fromPath('imagefile', image));
var response = await request.send().catchError((error) {
throw error;
});
response.stream.transform(utf8.decoder).listen((value) async {
return await http
.post(
_url,
headers: {
'content-type': 'application/json',
'authorization': 'auth'
},
body: json.encode({data}),
)
///// PROBLEM AREA //////
.then((value) async {
final _extractedData = await jsonDecode(value.body);
if (value.statusCode == 201) {
return true;
} else {
return false;
}
}).catchError((error) {
throw error;
});
});
}
Ok, for the next visitors to this page, the correct usage of MultipartRequest class should like this:
var uri = Uri.parse('https://example.com/create');
var request = http.MultipartRequest('POST', uri)
..fields['user'] = 'nweiz#google.com'
..files.add(await http.MultipartFile.fromPath(
'package', 'build/package.tar.gz',
contentType: MediaType('application', 'x-tar')));
var response = await request.send();
if (response.statusCode == 200) print('Uploaded!');

No response message after calling an API

Future<EventObject> addStudentToSubject(String studentCode, String subjectid) async {
try {
final encoding = APIConstants.OCTET_STREAM_ENCODING;
final response = await http.post('${APIConstants.API_BASE_LIVE_URL}/controller_educator/add_student_to_subject.php',
headers: {
'Accept': 'application/json',
},
body: {
'stud_code': studentCode,
'subj_id': subjectid
},
encoding: Encoding.getByName(encoding)
);
print("YAWA" + response.body);
} catch (Exception) {
return EventObject();
}
}
Is there something wrong with my code why i theres no response message??
Logcat just says "I/flutter ( 5013): YAWA"
Don't know what i'm missing.
I do not believe your API does not work in Postman. Can you indicate what status code did you get in Postman?
The problem in your code is your not checking the status code response of your API. The POST request you have called has probably had an empty body. Some POST request only returns the status code.
You should always check the status code of the API. If it returns 200 means your API has processed your request successfully.
final encoding = APIConstants.OCTET_STREAM_ENCODING;
final response = await http.post('${APIConstants.API_BASE_LIVE_URL}/controller_educator/add_student_to_subject.php',
headers: {
'Accept': 'application/json',
},
body: {
'stud_code': studentCode,
'subj_id': subjectid
},
encoding: Encoding.getByName(encoding)
);
print(${response.statusCode});
if (response.statusCode == 200) {
String data = response.body;
print(data);
} else {
print(response.statusCode);
}