Flutter: response on http post returns empty - android

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
}

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

How to fix exception : Unhandled Exception: Connection closed before full header was received

I send request and i have an exception
this is model class:
class User{
String mobileId , username;
User({this.username,this.mobileId});
factory User.fromJson(Map<String, dynamic> json){
return User(
username: json['userName'],
mobileId: json['mobileId'],
);
}
}
this is the function which i send request
Future<User> sendRequest(String mobileId , String username)async{
http.Response response = await http.post('http://94.237.88.194:8080/player',
body:jsonEncode(<String,String>{
'userName' : username,
'mobileId' : mobileId,
}),
);
print(response.statusCode);
return User.fromJson(jsonDecode(response.body));
}
I have found the solution
I added header to post function
Map<String, String> header = {"Content-Type": "application/json"};
and the function become:
Future<User> sendRequest(String mobileId , String username)async{
print('5');
Map<String, String> header = {"Content-Type": "application/json"};
http.Response response = await http.post('http://94.237.88.194:8080/player',headers: header,
body:jsonEncode(<String,String>{
'userName' : username,
'mobileId' : mobileId,
}),
);
print('4');
print(response.statusCode);
print(response.body);
return User.fromJson(jsonDecode(response.body));
}

Flutter HTTP post request sending list of objects

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.

Network Request POST with parameterized header

I need reference how to use header into the flutter.
I am passing below values for the header .
php-auth-user : test
php-aut-pw : test123
Here is my code for the main.dart
var url = "http:.../public/v1/login";
var body = json.encode({"account_id": "3","email":"saty#xyz.com","password":"admin123"});
this is header which i have used
Map headers = {
'Content-type' : 'application/json',
'php-auth-user':'test'
'php-auth-pw':'test123'
};
final response =
http.post(url, body: body, headers: headers);
final responseJson = json.decode(response.body);
print(responseJson);

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