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);
Related
i tried to send notification to another device when the app is terminated using workManager
it does not work, however the same function works if i use it without workManager
here is the code
in the main
await Workmanager().initialize(callBAckDispatcher, isInDebugMode: true);
callBackDispathcer
callBAckDispatcher() {
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
Workmanager().executeTask((taskName, inputData) async {
if (taskName == "t") {
int id = 7
await sFunction(id, await returnUserName());
}
return Future.value(true);
});
}
sFunction
sFunction(int id, String sender) async {
List<Map> response =
await SQLdb().readData('''SELECT * FROM `timer_chat` WHERE id = $id
''');
String reciever = response[0]['reciever'];
String message = response[0]['message'];
try {
String currentToken = await auth.getusertoken(reciever);
auth.sendnotify("my app",
"your message has been sent: " + message, "1", currentToken);
} catch (e) {
print("notification did not send: " + e.toString());
}
}
finally sendnotify
sendnotify(String title, String body, String id, String token) 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(),
"name": "me",
"lastname": "wolf"
},
"to": token
},
),
);
} catch (e) {
print("something went wrong in notiiiii" + e.toString());
}
}
i'm sending notifications using firebase cloud messaging API. it worked fine inside the app but in workManager it does not. any idea why?
thank you
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);
}
}
I am try to post an note to my API in Strapi but I have that error
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type '_InternalLinkedHashMap<String, String>' is not a subtype of type 'String' in type cast
that is my code
Map<String, String> header = {
"Authorization": "Bearer ${sharedp!.getString('token')}"
};
addPosts() async {
var response = await http.post(
Uri.parse(post_note),
body: {
"data": {
"title": "upload api",
"content": "upload api to the user and show it in the app by id",
"userid": sharedp!.getString('id')
}
},
headers: header,
);
var responsebody = jsonDecode(response.body);
print(responsebody);
return responsebody;
}
then that how I make post in postman
{
"data":{
"title":"upload api",
"content":"upload api to the user and show it in the app by id",
"userid":1
}
}
You can just wrap the json in a model class and obtain what you want by doing the following,
class ApiRequestData {
/*
{
"title": "upload api",
"content": "upload api to the user and show it in the app by id",
"userid": 1
}
*/
String? title;
String? content;
int? userid;
Map<String, dynamic> __origJson = {};
ApiRequestData({
this.title,
this.content,
this.userid,
});
ApiRequestData.fromJson(Map<String, dynamic> json) {
__origJson = json;
title = json['title']?.toString();
content = json['content']?.toString();
userid = json['userid']?.toInt();
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['title'] = title;
data['content'] = content;
data['userid'] = userid;
return data;
}
Map<String, dynamic> origJson() => __origJson;
}
class ApiRequest {
/*
{
"data": {
"title": "upload api",
"content": "upload api to the user and show it in the app by id",
"userid": 1
}
}
*/
ApiRequestData? data;
Map<String, dynamic> __origJson = {};
ApiRequest({
this.data,
});
ApiRequest.fromJson(Map<String, dynamic> json) {
__origJson = json;
data = (json['data'] != null) ? ApiRequestData.fromJson(json['data']) : null;
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
if (data != null) {
data['data'] = this.data!.toJson();
}
return data;
}
Map<String, dynamic> origJson() => __origJson;
}
Now once you construct your ApiRequest modal object like following,
setState(() => _isLoading = true); // If you intend to display a ProgressIndicator in the body while loading..
var id = await sharedp!.getString('id');
var req = ApiRequest(
data: ApiRequestData(
title: "upload api",
content: "upload api to the user and show it in the app by id",
userId: id,
),
);
var response = await http.post(
Uri.parse(post_note),
body: jsonEncode(req.toJson()),
headers: header,
);
var responsebody = jsonDecode(response.body);
setState(() => _isLoading = false); // To now display widgets with the loaded data..
Pretty sure this helps..
This is my code below, i'm stuck please help. How to set flutter POST method using DIO?
Map<String, dynamic> toJson() {
return {
'id': id,
"name": name,
"telNumber": telNumber,
"email": email,
"age": age
};
}
String postToJson(Post data){
final dyn = data.toJson();
return json.encode(dyn);
}
Future<http.Response> createPost(Post post) async {
final response = await http.post(
"$baseUrl/users",
headers: {
"content-type": "application"
},
body: postToJson(post));
return response;
}
This method works in http
BaseOptions options = new BaseOptions(
baseUrl: $baseUrl,
connectTimeout: 10000,
receiveTimeout: 10000,);
final dioClient = Dio(options);
try{
final response = await dioClient.post("/users", data: FormData.fromMap(
postToJson(post))
),);
return response;
} catch (e) {
throw (e);
}
Put this code inside the function
you can create a new function and call this from anywhere:
Future<Null> SendPost() async {
Response response;
BaseOptions options = new BaseOptions(
baseUrl: "https://your.url",
connectTimeout: 6000,
receiveTimeout: 3000,
);
Dio dio = new Dio(options);
FormData formData = new FormData.fromMap({
"post_data1": value,
"post_data2": value,
});
try {
response=await dio.post("/page.php", data: formData);
return response;
} catch (e) {
print('Error: $e');
}
}