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);
Related
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));
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}');
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.
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()}");
});
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'
});