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

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

Related

Retrieving data from http web call in flutter into a list object always empty

List is always empty even though body has contents. I am new to flutter so bare with me if this is basic. I am wanting to get back a list of station data I am coming from a c# background so forgive me if am missing something simple the test string body has the items and can see the items when i debug
class HttpService {
final String url = "url hidden";
final String host = 'url hidden';
final String apiSegment = "api/";
// ignore: non_constant_identifier_names
void login(email, password) async {
try {
Map<String, String> body = {
'username': email,
'password': password,
};
Map<String, String> headers = {'Content-Type': 'application/json'};
final msg = jsonEncode(body);
Response response =
await post(Uri.parse("$url/Login"), headers: headers, body: msg);
if (response.statusCode == 200) {
var data = jsonDecode(response.body.toString());
print(data['jwtToken']);
print('Login successfully');
final prefs = await SharedPreferences.getInstance();
await prefs.setString('jwtToken', data['jwtToken']);
List<Stations> stationData = await getStationData('11');
var test = stationData;
} else {
print('failed');
}
} catch (e) {
print(e.toString());
}
}
Future<List<Stations>> getStationData(String stationId) async {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('jwtToken');
const String path = 'Station/GetAllStationData';
final uri = Uri.parse('$url/api/$path')
.replace(queryParameters: {'stationId': stationId});
List<Stations> stationData = <Stations>[];
try {
Response res = await get(uri, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
// 'Authorization': 'Bearer $token',
});
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
var body2 = body.toString();
stationData = body
.map(
(dynamic item) => Stations.fromJson(item),
)
.toList();
} else {
throw "Unable to retrieve posts.";
}
} catch (e) {
print(e.toString());
}
return stationData;
}
}
I am calling my function from the same class
List<Stations> stationData = await getStationData('11');
Data from body
Actually the problem is you are returning the data after the end of try catch.
Try this
Future<List<Stations>> getStationData(String stationId) async {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('jwtToken');
const String path = 'Station/GetAllStationData';
final uri = Uri.parse('$url/api/$path')
.replace(queryParameters: {'stationId': stationId});
try {
Response res = await get(uri, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
// 'Authorization': 'Bearer $token',
});
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
final stationData = List<Stations>.from(body.map((item) => Stations.fromJson(item))); // made some changes
return stationData;
} else {
throw "Unable to retrieve posts.";
}
} catch (e) {
rethrow;
}
}
I hope this will help you

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']);

How can i add headers for authorization and content-type flutter

i have this code for to call api;
how can I add authorization and content-type headers to this?
final url = Uri.parse('https://api.collectapi.com/economy/hisseSenedi');
var counter;
var hisseResult;
Future callHisse() async {
try{
final response = await http.get(url);
if(response.statusCode == 200){
var result = hisselistFromJson(response.body);
if(mounted);
setState(() {
counter = result.data.length;
hisseResult = result;
});
return result;
} else {
print(response.statusCode);
}
} catch(e) {
print(e.toString());
}
}
Thanks for your help
you can do this:
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': '<Your token>'
};
final response = await http.get(url,headers:requestHeaders);

Common method for flutter api calls

Is there any example that I can refer to about Common class/method for flutter API calls(GET,POST,...) in flutter? I have handled all the API requests in a common method in react native, I'm not sure how to implement it in flutter.
you have to call getRequest using url parameter
Future<Response> getRequest(String url) async {
Response response;
try {
response = await _dio.get(url,
options: Options(headers: {
HttpHeaders.authorizationHeader:
'Bearer $accessToken'
}));
print('response $response');
} on DioError catch (e) {
print(e.message);
throw Exception(e.message);
}
return response;
}
here is the post method
Future<Response> posRequestImage(String url, data) async {
try {
response = await _dio.post(
url,
data: formData,
options: Options(headers: {
HttpHeaders.authorizationHeader:
'Bearer $accessToken'
}),
);
if (response.statusCode == 200) {
return response;
}
print('post response $response');
} on DioError catch (e) {
print(e.message);
throw Exception(e.response?.statusMessage);
}
return response;
}
You can create a class to handle it. For example, this is my class to handle all service for user model
import 'package:http/http.dart' as http;
class UserService {
var baseUrl = URL.devAddress;
Future<User> getUser() async {
final response = await http.get(
Uri.parse(baseUrl + "user/1")
);
if (response.statusCode == 200) {
final data = json.decode(response.body);
return data
} else {
throw Exception("Failed");
}
}
}
Future<void> getUser(String username) async {
Uri uri = Uri.parse('https://example.com');
try {
Map<String, dynamic> params = new HashMap();
params['username'] = username;
final response = await client.post(uri,
body: jsonEncode(params),
);
print("response ${response.body}");
} on FetchDataException {
throw FetchDataException("No Internet connection");
}
}

fetching the response from API and dealing with the errors / converting Bytestreem to Map in flutter

I am trying to communicate with a PHP backend using API but I can not reach the body of the response.
I got the base code from the postman.
And here is the data of the body response:
I need to reach the message, and the errors to show them in the UI, the problem is response.stream it's type is Bytestreem and I can not convert it to Map
My code:
Future<void> _authenticateUp(String email, String password,
String passwordconfirmation, String username, String name,
{String phonenumber}) async {
var headers = {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
};
var request = http.MultipartRequest('POST', Uri.parse('$siteUrl/register'));
request.fields.addAll({
'email': email,
'password': password,
'password_confirmation': passwordconfirmation,
'username': username,
'name': name,
'phone_number': phonenumber
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
try {
if (response.statusCode == 200) {
await response.stream.bytesToString().then((value) {
print(value);
});
} else {
// here I want to print the message and the errors
}
} catch (e) {
throw e;
}
}
Add this As for Error your statusCode is not 200
try {
if (response.statusCode == 200) {
await response.stream.bytesToString().then((value) {
print(value);
});
} else {
await response.stream.bytesToString().then((value) {
print(value);
var jsonResponse = json.decode(response.body.toString());
var nameError = jsonResponse["errors"]["name"][0];
var emailError = jsonResponse["errors"]["email"][0];
var usernameError = jsonResponse["errors"]["username"][0];
var passwordError = jsonResponse["errors"]["password"][0];
//now can print any print(emailError);
});
}