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

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():

Related

Flutter API Post Method Can not Send Data to SQL server localhost. Show Error "HTTP Error 400. The request hostname is invalid"

This is My Flutter Code--
void send() async
{
var bb=json.encode(listModel.toJson());
var response = await http.post(Uri.parse(
"http://10.0.2.2:1066/api/Storedata/Add"),
body: bb,
headers: {"Content-type": "application/json"},);
if (response.statusCode == 201)
{
print("Done");
}
else
{
print(response.body);
print(response.statusCode);
}
}
In "bb" variable all data show in json format when i debugged. but show this error "HTTP Error 400. The request hostname is invalid". Please Help!!!!

Api is working in postman but response always return 500 in flutter

My rest api is working successfully. When I send post request in flutter with Dio. Service always return 500 internal server error.
header
post request
Dio Options
To create a form data use this
var formData = FormData.fromMap({
'user': 'username',
'pass': 'password',
});
response = await dio.post('apiendpoint', data: formData);
I think you are missing the content-type in your header.. based on what your remote accepts either 'application/x-www-form-urlencoded' or 'application/json'
var data = {"phone": mobileNumber, "password": password};
var dio = Dio();
dio.options.headers['content-Type'] = 'application/x-www-form-urlencoded';
try {
var response = await dio.post(ApiUrl.baseUrl + url, data: data);
print(response);
} on DioError catch (e) {
print(e);
}
you can try this way :
var formData = {
'user': 'username',
'pass': 'password',
};
response = await dio.post('apiendpoint', data: jsonEncode(formData));

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

Parse server (Back4App) cloud function httpRequest returns 'invalid function' error

I am trying to send FCM notifications directly on the firebase POST url. When i comment out the httpRequest block, the function executes properly.
When i uncomment the block, it starts to give me 'invalid function (141)' error on Android app.
The request works and delivers notification via postman.
Here's my cloud function:
const httpResponse = await Parse.Cloud.httpRequest(
url: 'https://fcm.googleapis.com/fcm/send/',
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Authorization': 'key='+fcm_key
},
body:{
'data':{
'key1': 'value1',
'key2' : 'value2',
'key3': 'value3',
'key4': 'value4',
'key5': 'value5',
'key6': 'value6',
'key7': oneParseObject.get('someColumnName')
},
'registration_ids': new Array(targetFcmToken)
}
);
return 'Done with status code '+httpResponse.status;
Curly braces inside function call were missing.
Solution:
const httpResponse = await Parse.Cloud.httpRequest({
url: 'https://fcm.googleapis.com/fcm/send/',
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Authorization': 'key='+fcm_key
},
body:{
'data':{
'key1': 'value1',
'key2' : 'value2',
'key3': 'value3',
'key4': 'value4',
'key5': 'value5',
'key6': 'value6',
'key7': oneParseObject.get('someColumnName')
},
'registration_ids': new Array(targetFcmToken)
}
});
return 'Done with status code '+httpResponse.status;

How to display server response for HTTP errors in React Native

I'm working on a React Native app. We recently made a change to an API call, where it can respond with 500 and an error message detailing the problem so it can be presented to the user. The API response looks like:
{
"error": ["Renter contact info for User 1 missing"]
}
On the client, we're using the standard fetch() method to asynchronously make our request, and resolving the Promise in order to pull the response object out. When I log the response after a call that should trigger a 500, the object looks like:
{type: "default", status: 500, ok: false, statusText: undefined, headers: Headers…}
Here's our internal request() method we use for all API calls:
export function request(endpoint:string, parameters:Object, method:string = HTTP.get, timeout:number = 3000):Promise{
return new Promise(async (resolve, reject) => {
const payload = {
method,
headers: {
'Accept': CONTENT_TYPE,
'Content-Type': CONTENT_TYPE,
'Authorization': `Basic ${base64.encode(Config.API_TOKEN)}`,
'Auth-Token': await Agents.authToken,
},
body: JSON.stringify(parameters),
}
fetch(apiUrl(endpoint), payload)
.then(response => {
if(!response.ok) {
// ******************
// this is where the 500 error state is caught, but my response object doesn't contain the message sent from the server.
reject(response)
// ******************
}
return response
})
.then(resolve)
.catch(reject)
})
}
How can I ensure the response object contains the error message from the server so I can properly display it to my user?
fetch(apiUrl(endpoint), payload)
.then(response => {
if(!response.ok) {
response.json().then(function(data) {
console.log(data);// your error response
},function(error) {
//json error
});
reject(response)
// ******************
}
return response
})
response is a ReadableStream object. You need to use .json() to parse

Categories

Resources