request from flutter app mobile not working but it working in web - flutter

i am already work with this code
months ago and it work correctly but now when go to run app i have this problem but it work when run it in web
var response = await http.get(Uri.parse("url"),
headers: {
HttpHeaders.authorizationHeader : "Bearer $token",
HttpHeaders.contentTypeHeader: "application/json"
}) ;
print(+response.statusCode.toString());//status code : 500 phrase reason : internal server error

Try it This Way ( set Url -> Header -> Get Responser -> Try catch -> Return )
Future<dynamic> getSchools() async {
var url = Uri.parse(base_url + '/api/user/get_schools');
final http.Response response = await http.get(
url,
headers: <String, String>{
'Content-Type': 'application/json',
},
);
if (response.statusCode == 200) {
if (kDebugMode) {
print("200 status");
}
List<School> student = (json.decode(response.body) as List).map((data) => School.fromJson(data)).toList();
return student;
} else {
return "false";
}
}

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.

How to Get data from previous date and future date in flutter api call

I am working on an app for event management, I want to retrieve event data from api call for past date and future date.
I am using the below code. But no luck.
Future<List<dynamic>> getPastEventsData() async {
var token = box.read('token');
try {
final response = await get(
BaseClient().apiUrl.toString() +
'api/event/?event_date<' +
DateFormat('y-MM-d').format(DateTime.now()),
headers: {'Authorization': 'token $token'},
);
if (response.status.hasError) {
return Future.error(response.statusText.toString());
} else {
return response.body;
}
} catch (exception) {
return Future.error(exception.toString());
}
}
Future<List<dynamic>> getFutureEventsData() async {
var token = box.read('token');
try {
final response = await get(
BaseClient().apiUrl.toString() +
'api/event/?event_date>' +
DateFormat('y-MM-d').format(DateTime.now()),
headers: {'Authorization': 'token $token'},
);
if (response.status.hasError) {
return Future.error(response.statusText.toString());
} else {
return response.body;
}
} catch (exception) {
return Future.error(exception.toString());
}
}
Please help me. Thanks
var url = Uri.parse(SystemConfiguration.baseUrl +
SystemConfiguration.leaveCalenderEndpoint);
var response = await http.post(
url,
body: json.encode({
"pageSize": 100,
"pageIndex": 0,
"fromDate": DateFormat('yyyy-MM-dd').format(DateTime(
DateTime.now().year - 2,
DateTime.now().month,
DateTime.now().day)),
"toDate": DateFormat('yyyy-MM-dd').format(DateTime(
DateTime.now().year + 2,
DateTime.now().month,
DateTime.now().day))
}),
headers: {
"content-type": "application/json",
"accept": "application/json",
"Authorization": "Bearer " + accessToken
},
);
var jsonResponse = json.decode(response.body.toString());
Thanks #Tasnuva oshin for your answer, though I have solved the problem in alternate way: Through a filter action in my resulted list of API response in my view part. The working code is as below:
For past data:
_eventController.eventData.where((e) => DateTime.parse(e['event_date'])
.isBefore(DateTime.parse(
DateFormat('y-MM-d').format(
DateTime.now()))))
.toList()
For future data:
_eventController.eventData.where((e) => DateTime.parse(e['event_date'])
.isAfter(DateTime.parse(
DateFormat('y-MM-d').format(
DateTime.now()))))
.toList()
eventData is my resulted list from the API call response.

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) {
}

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);
}