Infobip SMS bulk messages API with flutter/dart - flutter

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

Related

How to make api class where api response start with array?

How to make api class where api response start with array ?
Api Response :-
[
{
"reqList": [
{
"_id": "123448478478",
"username": "12345",
"amount": 4100
},
],
"_id": "636e2c5cf0142eed68343335",
"username": "umesh-rajput",
"amount": 95
}
]
We can handle this response as a list of individual JSON objects inside the response array.
This is general Pseudo code.
class DataProvider{
List<YourModel> getDate(String URL) async {
var response = await http.get(url);
if(resonse.statuscode == 200)
{
var List<YourModel> modelList =
response.body.map((jsonObject)=>YourModel.toJson(jsonObject);
);
return modelList;
}
return [];
}
}
Future<List<MODEL NAME>> getAllBetNotification() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var token = prefs.getString('userToken');
url = 'API URL';
var response = await http.get(Uri.parse(url), headers: {
'Authorization': 'YOUR TOKEN',
});
if (response.statusCode == 200 || response.statusCode == 201) {
// print(response.body);
var list1 = (jsonDecode(response.body) as List)
.map((dynamic i) =>
UserNotificationModel.fromJson(i as Map<String, dynamic>))
.toList();
return list1;
} else {
print('do not send notification');
return [];
}
}

DioError [DioErrorType.other]: Converting object to an encodable object failed: _LinkedHashSet len:1 Flutter

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

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 post request parse

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

How to set flutter POST method using DIO?

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