Flutter: http.post the object - flutter

I am trying to send a http.post request with multiple variables.
var acc = {
'acc_type': 'normal',
'time': 'Jan 27',
};
var what = await http.post(
'http://localhost:7200/api/activity/addactivity',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(
<String, dynamic>{
'userId': 'aaa111',
'location': 'hellooooo',
'acc': acc
},
),
);
When I remove acc: acc, Flutter sends requests. However, I need to send var acc value to the server in order to post it. I tried to encode it to JSON the http.post() function. It seems not working. How can I send the object as part of the post request?

This will work.
import 'dart:convert';
//....
var what = await http.post(
'http://localhost:7200/api/activity/addactivity',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: json.encode(
<String, dynamic>{
'userId': 'aaa111',
'location': 'hellooooo',
'acc': acc
},
),
);

var acc = {
'acc_type': 'normal',
'time': 'Jan 27',
};
var what = await http.post(
'http://localhost:7200/api/activity/addactivity',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body:(
<String, dynamic>{
'userId': 'aaa111',
'location': 'hellooooo',
'acc': acc.toString(),
},
),
);

Related

i want to send notification when receive a meesage in my chat app but it didn't work

i tried method using firebase_messaging: 7.0.1 but now its firebase_messaging: 14.0.2.
i got this error :
Converting object to an encodable object failed: Instance of 'Future<String?>'
sendNotif(String? title, String? body, String? id) async {
try {
await http
.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=$serverToken',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': body.toString(),
'title': title.toString()
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': id.toString(),
},
'to': FirebaseMessaging.instance.getToken(),
},
),
)
.then((value) => (value) {
print("send succeffuly");
});
} catch (e) {
print("THe ERROR : $e");
}
}
As the error message says, FirebaseMessaging.instance.getToken() returns a Future<String>, while the post API expects only current (non-Future) values.
The simplest fix is to await the value:
'to': await FirebaseMessaging.instance.getToken(),

Digest Authentication not working with HttpClient

I have used all approaches to Post data using digest authentication but it is not working?
HttpClient authenticatingClient = HttpClient(); authenticatingClient.addCredentials( Uri.parse( 'http://202.142.0000', ), 'aa',=>realm HttpClientDigestCredentials('admin', 'admin'), ); clients = https.IOClient(authenticatingClient); clients .post( Uri.parse( 'http://202.142.0000', ), headers: {'Content-Type': 'application/json'}, body: json.encode({ "Protocol": "a[enter image description here][1]", "Packets": [ { "Id": 1, "Type": "PumpGetStatus", "Data": {"Pump": 1} } ] }), ) .then((value) { print(value.headers); });
Try this code and report the results.
You'll be aiming for the code shown in main (which uses pre-authentication, as long as you know the realm in advance). Somehow, I'm guessing that aa isn't the valid realm.
The code in main2 can be substituted temporarily. Even though it will definitely fail, it will print out the realm, etc. to confirm the true values.
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart' as ioc;
void main() async {
final postMap = {
'Protocol': 'o',
'Packets': [
{
'Id': 1,
'Type': 'PumpGetStatus',
'Data': {'Pump': 1}
}
]
};
final uri = Uri.parse('http://202.142.x.x');
final authenticatingClient = HttpClient();
authenticatingClient.addCredentials(
uri,
'aa', // is this actually the realm, or is it a guess?
HttpClientDigestCredentials('admin', 'admin'),
);
http.Client client = ioc.IOClient(authenticatingClient);
final response = await client.post(
uri,
headers: {'Content-Type': 'application/json'},
body: json.encode(postMap),
);
print(response.statusCode);
print(response.body);
client.close();
}
void main2() async {
final postMap = {
'Protocol': 'o',
'Packets': [
{
'Id': 1,
'Type': 'PumpGetStatus',
'Data': {'Pump': 1}
}
]
};
final uri = Uri.parse('http://202.142.x.x');
final authenticatingClient = HttpClient();
authenticatingClient.authenticate = ((u, s, r) async {
print('uri=$u scheme=$s realm=$r');
return false;
});
http.Client client = ioc.IOClient(authenticatingClient);
final response = await client.post(
uri,
headers: {'Content-Type': 'application/json'},
body: json.encode(postMap),
);
print(response.statusCode);
print(response.body);
client.close();
}

Flutter api showing 'Required parameter missing or invalid'

Flutter rest API showing 'Required parameter missing or invalid'
main() async {
final data = {
'customer': {
'first_name': 'Karla',
'last_name': 'Mullins',
'email': 'KarlaMullins#mailinator.com',
'phone': '+15142546011',
'verified_email': true,
'addresses': [
{
'address1': '123 Oak St1',
'city': 'Ottawa1',
'province': 'ON',
'phone': '555-1212',
'zip': '123 ABC',
'last_name': 'Mullins',
'first_name': 'Karla',
'country': 'CA',
}
]
}
};
var json = jsonEncode(data);
String username = 'u';
String password = 'p';
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
var response = await http.post(url',
headers: <String, String>{
'authorization': basicAuth,
"Accept": "application/json",
},
body: json,
);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
calling rest api with basic authorisation from flutter dart showing Response status: 400
and Response body: {"errors":{"customer":"Required parameter missing or invalid"}}.
Change Accept into "content-type":"application/x-www-form-urlencoded
Or application/json, depending on your api.

Send notification over device using FCM and Flutter

currently I am trying to send a notification to multiple device. I already read the documentation on how to send notification to device group , they mentioned that I need to use registration_ids: [...] instead of to: token. And I also read somewhere that they mentioned about notification_key which is it will enabled to send the notification to the other device. So, I'm stuck on finding the key. But then, after few days browsing, I found out that here stated that the notification_key already deprecated. So, I would like to ask if any of you guys know how to send notification to multiple device without using console.
This I my code segment to send push the notification:
try {
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
// Uri.parse('https://fcm.googleapis.com/fcm/notification'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'key=$serverKey',
'project_id':'....',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': 'this is a body2',
'title': 'this is a title'
},
'priority': 'high',
'data': <String, dynamic>{
'click_action':
'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done'
},
'registration_ids': ['fbN9aYoORhihksrTo7j5D2:APA91b......', 'fArqpgKrTJ0fL8SUKddy2F:APA91bFWf1cnVMS8.......'],
// 'to': _token,
},
),
);
} catch (e) {
print("error push notification");
}
It work fine if I used to instead of registration_ids, but the things is as I understand is to is used if I want to send notification only for one device.
I already stuck with this issue for three days and still not found any solution. Most of them are using console instead. Your help will really made my day. Thank you in advance!
I found a solution and its work!
var serverKey =
'AAAAUb...';
QuerySnapshot ref =
await FirebaseFirestore.instance.collection('users').get();
try {
ref.docs.forEach((snapshot) async {
http.Response response = await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=$serverKey',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': 'this is a body',
'title': 'this is a title'
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done'
},
'to': snapshot.data() ['tokenID'],
},
),
);
});
} catch (e) {
print("error push notification");
}

flutter send data to server (statusCode 500)

I am new to flutter and am trying to send data to the server. I followed a tutorial, but it did not work it give me a status code 500:
void signUp() async {
http.Response response = await http.post(
"https://my-shop-server.herokuapp.com/api/v1/users/signup",
body:jsonEncode(<String, String>{
"name" :"test" ,
"email" : "test180#gmail.com" ,
"password" : "qwert" ,
"passwordConfirm" : "qwert"
})
);
print(response.body);
print(response.statusCode);
}
You do not correctly pass the body. You need to jsonEncode your key-value pair like this:
http.Response response = await http.post(
"https://my-shop-server.herokuapp.com/api/v1/users/signup",
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body:jsonEncode(<String, String>{
"name" :"test" ,
"email" : "test180#gmail.com" ,
"password" : "qwert" ,
"passwordConfirm" : "qwert"
});
Please carefully look here.