Flutter HTTP post request sending list of objects - android

I have successfully got a 200 response code from the server but my API returns response code of 0. When I try to send a request in the postman it response to 1. Maybe I do have something missing in my JSON to send in the body. I'm new to flutter and I would like to send a post HTTP request with a body of list of objects like below: I really appreciate any help.
[
{
"product_id": 14,
"quantity": 3,
"payment": "COD"
},
{
"product_id": 3,
"quantity": 2,
"payment": "COD"
}
]
This is my function for HTTP post:
Future<dynamic> checkItem({Map headers, body, encoding}) async {
Map<String, String> headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer $token'
};
try {
final response = await http.post(
'${_url}transactions/check',
headers: headers,
body: body,
encoding: Encoding.getByName("utf-8"));
if (response.statusCode == 200) {
String data = response.body;
return jsonDecode(data);
} else {
print(response.statusCode);
}
} catch (error) {
print(error);
}
}
This is how I call the function which I pass my JSON:
List<String> chckList = checkoutList.map((e) => json.encode(e.toJson())).toList();
String strBody = json.encode(chckList);
final res = await interface.checkOutItem(body: strBody);
This is my toJson in my Model object:
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['product_id'] = this.product_id;
data['quantity'] = this.quantity;
data['payment'] = this.payment;
return data;
}

The request in your code seems to all line in place. The issue likely lies on the API you're using that's unable to handle to handle the payload that you're sending.

Related

How to send Binary encrypted data in flutter POST with request encoding :null ? ; which is working in node js properly

According to node.js Documentation encoding : null when binary data to be sent via Api,
https://www.npmjs.com/package/request in this link below mentioned explanation is found.
encoding - encoding to be used on setEncoding of response data. If
null, the body is returned as a Buffer. Anything else (including the
default value of undefined) will be passed as the encoding parameter
to toString() (meaning this is effectively utf8 by default).
Note: if you expect binary data, you should set encoding: null.
Now I have achieve the same thing in flutter/dart and this encoding parameter is not accepting null as here in node.js they have mentioned.
I want to know how to make this same Post request from Flutter/dart or at least android/java.
var enc = AESCrypt.encrypt(key, iv, JSON.stringify(obj_j));
var output = new Buffer.from(enc, 'hex'); // Buffer
function test() {
console.time("XXX");
request.post({
headers: {
'content-type': 'application/json'
}, //required, or webserver will ignore it application/json multipart/form-data
url: 'http://192.168.29.210/deviceid/read', // webserver url
encoding:null,
body: output
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.timeEnd("XXX");
body = AESCrypt.decrypt(key, iv, body);
//body is decrypted http response, can be parsed with json method
fs.writeFile('input.json', body, function (err) {
if (err) {
return console.error(err);
}
});
}
});
};
Adding code the What i have tried in flutter
var headers = {'Content-Type': 'application/json'};
var request =
http.Request('POST', Uri.parse('http://192.168.29.210/deviceid/read'));
request.body = encryptedText;
request.encoding = null ; // here this null parameter is not acceptable
request.encoding = Encoding.getByName("utf-8")); // only this option is available to add in flutter
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
Even in post man this encoding variable is not present to set it.
Use below flutter framework method
Future<Response> post(Uri url,
{Map<String, String>? headers, Object? body, Encoding? encoding}) =>
_withClient((client) =>
client.post(url, headers: headers, body: body, encoding: encoding));
How to use
final url = Uri.parse('$urlPrefix/posts');
final headers = {"Content-type": "application/json"};
final json = '{"title": "Hello", "body": "body text", "userId": 1}';
final response = await post(url, headers: headers, body: json,encoding:null); //here this null parameter is not acceptable
My Final working code is
var headers = {'Content-Type': 'application/json'};
final response = await http.post(
Uri.parse('http://192.168.29.210/deviceid/read'),
headers: headers,
body: encryptedText,
encoding: null);
if (response.statusCode == 200) {
String res = response.body.toString();
//String data = AesEncryption().decryption(res);
print('Body: ${response.body.toString()}');
} else {
print(response.reasonPhrase);
}
print('Status code: ${response.statusCode}');

Flutter: response on http post returns empty

I'm trying to get the response after making a post to an api, but the response (which is a json) doesnt come, when i try to print the line is empty.
Can someone help me to figure out what i'm making wrong?
I have printed the status code just for testing and its returning 500, could this be related?
Future<void> _login() async {
Map<String, dynamic> newLogin = Map();
newLogin["user"] = _usuarioController.text.trimLeft();
newLogin["pass"] = _senhaController.text.trimLeft();
Map<String, String> headers = new Map<String, String>();
headers["Content-type"] = "application/json";
headers["Accept"] = "application/json";
int timeout = 2;
http.Response response = await http
.post('https://sistema.hutransportes.com.br/api/login.php',
headers: headers, body: jsonEncode(newLogin), encoding: utf8)
.timeout(Duration(seconds: timeout));
print(newLogin);
print(response.statusCode);
print(response.body); //Where the empty response comes
}

DioError [DioErrorType.RESPONSE]: Http status error [400] Exception

I am developing a Flutter Restful web application and the web api backend as asp.net core. When i try to send the form data using post request it is throwing this error
DioError [DioErrorType.RESPONSE]: Http status error [400] Exception
Code
onPressed: () async {
String email_value = emailController.text;
String password_value = passController.text;
String fullname_value = fullnameController.text;
var repassword_value = repassController.text;
print("$email_value");
if (password_value == repassword_value) {
try{
Dio dio = Dio();
var body = jsonEncode(
{
'FullName': '$fullname_value',
'Email': '$email_value',
'Password': '$password_value'
}
);
print("Body" + body);
Response response = await dio.post("http://iamtv.chainuniverse.com/api/Accounts/Register",
data: body,
options: Options(
contentType: Headers.jsonContentType,
)
);
var jsonData = json.decode(response.data);
print(jsonData);
if (response.statusCode > 200 &&
response.statusCode < 250) {
print("Sucess");
await loginAction();
print("Registered");
}
else{
print(jsonData);
}
But when i send data manually without using textcontroller Text it works. Please help me to fix this
Working perfectly in POSTMAN
Late answer, may help you.
I was getting same error with Dio and form-data. It worked! after adding contentType
FormData formData = FormData.fromMap({
"image-param-name": await MultipartFile.fromFile(
imageFile.path,
filename: fileName,
contentType: new MediaType("image", "jpeg"), //add this
),
});
complete code
var dio = Dio();
String fileName = imageFile.path.split('/').last;
FormData formData = FormData.fromMap({
"image-param-name": await MultipartFile.fromFile(
imageFile.path,
filename: fileName,
contentType: new MediaType("image", "jpeg"), //add this
),
});
var response = await dio.post(
"url",
data: formData,
options: Options(
headers: {
"Authorization": auth-token
},
),
onSendProgress: (int sent, int total) {
debugPrint("sent${sent.toString()}" + " total${total.toString()}");
},
).whenComplete(() {
debugPrint("complete:");
}).catchError((onError) {
debugPrint("error:${onError.toString()}");
});

How to post int/integer value as json from dart/flutter

I am using asp.net core web API as back-end. There is a method that accepts a single integer value.
Method([FromBody] int value)
I want to post the integer value from dart/flutter.
I tried the following with the dart http package.
Http.post(url, body:0,headers:{"content-type":"application/json"}
Http.post(url, body:{0},headers:{"content-type":"application/json"}
Http.post(url, body:convert.jsonEncode(0),headers:{"content-type":"application/json"}
Http.post(url, body:convert.jsonEncode({0}),headers:{"content-type":"application/json"}
All my above tries failed with error
"Invalid argument: invalid request body "0""
I had the same problem when trying to send an HTTP request to an API that has an integer as one of its arguments(age). Dart wanted me to convert the int into a string and the API was not accepting the int as a string. Hence I was getting the same error and ended up in this question.
My solution was to store the input in a map, add a header {"content-type":"application/json"} and pass the map in the body arguement.
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<String> register_user() async {
var req_body = new Map();
req_body['username'] = 'John Doe';
req_body['age'] = 20; /* The integer */
final response = await http.post(
'http://127.0.0.1:8081/user/register',
headers: {'Content-Type': 'application/json'},
body: jsonEncode(req_body));
if (response.statusCode == 200) {
var object = json.decode(response.body);
return object.toString();
} else if (response.statusCode == 422) {
return 'Error';
} else {
return 'Can not connect to server';
}
}
Please refer my code
import
import 'package:http/http.dart' as http;
http request
var client = new http.Client();
client.post(Uri.encodeFull("Your url"), body: {
"param1": "value1",
"param2": 11, // integer value type
}).then((response) {
client.close();
if (this.mounted && response.statusCode == 200) {
//enter your code for change state
}
}).catchError((onError) {
client.close();
print("Error: $onError");
});
I hope it will help you.
PS:
var client = new http.Client();
var response = await client.post(Uri.encodeFull("Your Url"), body : "0", header : {/*Your headers*/"});
You can try this code.
Http.post(url, body:{"id": "0"},headers:{"content-type":"application/json"}
Can you try bellow one
var queryParameters = {
'value': '0'
};
var uri =
Uri.https('www.myurl.com', '/api/sub_api_part/', queryParameters); //replace between part and your url
var response = await http.get(uri, headers: {
HttpHeaders.contentTypeHeader: 'application/json'
});

flutter - no json is sent in the body of my http post

this is the code.
Future<http.Response> postRequest () async {
var url ='http://10.0.2.2:3000/api/message';
Map data = {
'message': '12345678901234567890'
};
//encode Map to JSON
var body = json.encode(data);
var response = await http.post(url,
headers: { "accept": "application/json", "content-type": "application/json" },
body: body
);
print("${response.statusCode}");
print("${response.body}");
return response;
}
postRequest();
// also tried this: headers: {"content-type":"application/json" },
In my python flask server, the post message is logging, but with empty body into it.
The flutter app is running on Android Virtual Device and the server is still running on http://0:0:0:0:3000/ and it's using request.get_json() in the method.
Using postman, everything works as expected on my server so I see the problem in the app.
postman details:
POST: http://localhost:3000/api/message
headers
KEY | VALUE
Content-Type | application/json
Body raw
{
"message": "opa"
}
also raised here: https://github.com/flutter/flutter/issues/39351
Try passing :
Future<http.Response> postRequest () async {
var url ='http://10.0.2.2:3000/api/message';
Map<String, String> data = { "message": "opa" };
var body = json.encode(data);
var response = await http.post(url,
headers: { "accept": "application/json", "content-type": "application/json" },
body: body
);
print(response.statusCode);
print(response.body);
return response;
}
postRequest().then((response){
print(response.body);
});
not sure if my finding is precious or not for community, but it seems that the URL was the problem. Everything works now, but I added a / in the end of the string in my flask app.
In Postman, I didn't have to do this. So if you have same problem, take care :)
The log from Flask server:
127.0.0.1 - - [30/Aug/2019 17:41:32] "POST /api/message/ HTTP/1.1" 200 -
opa
My Flask url is:
#app.route('/api/message/', methods=['POST'])
def function():

Categories

Resources