Flutter http - Invalid argument(s): Invalid request body when jsonEncode is used - flutter

Future<void> _sendData() async {
final url = Uri.https('websitename.tld', 'restricted/login');
try {
final response = await http.post(
url,
headers: {"Content-Type": "application/json"},
body: {
json.encode({
'username': 'UserName',
'userpass': 'UserPaZZw0rd',
})
},
);
} catch (err) {print(err);}
}
causes : flutter: Invalid argument(s): Invalid request body "{{"username":"UserName","userpass":"UserPaZZw0rd"}}".
if i make a call without json, code works like a charm.
jsonEncode instead of json.encode -> same result.
Any ideas?
Thanks!

Try this.
body: json.encode({
'username': 'UserName',
'userpass': 'UserPaZZw0rd',
}),

Related

how post api with authentication identifier and secret in flutter

i want fetch data by post method with identifier and secret in flutter
where should i add "identifier" and "secret" in post method?
in postman they added to body and that works but i couldnt add these to flutter code:
Future post(String url, var data) async {
String url = 'https://member.example.com/includes/api.php';
var data = {
'identifier': 'identifier code otm7LE8OzlBmprXn',
'secret': 'secret code SXZgmDpX8miT31PSRQ',
'action': 'GetInvoices',
'userid': 6414,
'orderby': 'date',
'responstype': 'json',
};
try {
final response = await http.post(
Uri.parse(url),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json',
},
body: jsonEncode(data),
);
} catch (e) {
print(e);
}
}
E/flutter ( 6118): result=error;message=Authentication Failed

Make a post HTTP

I follow the below code, but it seems not to work:
var body = jsonEncode(<String, String>{
'uid': uid,
'limit': '10',
'offset': '2',
'action': 'feed',
});
final response = await http.post(
Uri.parse('http://abc.or/fb/selectPosts.php'),
body: body,
);
if (response.statusCode == 200) {
List<Post> posts = [];
// If the server did return a 200 OK response,
// then parse the JSON.
print((jsonDecode(response.body)));
return List<Post>.from(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to update album.');
}
My API looks like this: http:/abc.or/fb/post.php?uid=aaaa&limit=10&offset=2&action=feed
try this.
import 'package:http/http.dart';
...
static const urlPrefix = 'https://jsonplaceholder.typicode.com';
...
Future<void> makePostRequest() async {
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);
print('Status code: ${response.statusCode}');
print('Body: ${response.body}');
}
Those are query fields not request body fields.
They are passed in the link or as queryparematers in a Uri
final response = await http.get(
Uri(
path: <your url without the queries(http://abc)>,
query: <Your queries as they are in the string (uid=aaaa&limit=10&offset=2&action=feed), you can use string interpolation to fix the values in or better still use queryparematers, not both>
queryParameters : <String, dynamic>{ 'uid': uid, 'limit': 10, 'offset': 2, 'action': feed },)
);
I use a get method which should be the standard for such url. Do confirm from whoever wrote the api if it is a uses a get or post method.

Flutter - How to send a POST request using HTTP in Dart?

I am using an API that converts HTTP to JSON and to get a response from the server I need to send a post request of HTML however i'm not sure how to do that?
This is my current implementation -
Future<String> test() async {
var link =
await http.get('https://example.com');
var body = parse(link.body);
return body.outerHtml;
}
Future<Album> createAlbum(String html) async {
final http.Response response = await http.post(
'https://www.html2json.com/api/v1',
headers: <String, String>{
'Content-Type': 'text/html; charset=UTF-8',
},
body: html,
);
if (response.statusCode == 200) {
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to create album.');
}
}
I call this is when my app starts like so,
#ovveride
void initState() {
test().then((body) => createAlbum(body)); //Output returns HTTP error 301, am I doing something wrong?
super.initState();
}
Checked the following code which worked for me.
Future<Album> createAlbum(String html) async {
final http.Response response = await http.post(
'https://www.html2json.com/api/v1',
headers: <String, String>{
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: html,
);
You need to change the Content-type to application/x-www-form-urlencoded; charset=UTF-8. This should do the trick.
Thanks to DARSH SHAH, I solved this using dio (https://pub.dev/packages/dio).
dynamic response;
Dio dio = Dio();
Future<dynamic> test() async {
dynamic link = await dio.get(
'https://example.com');
return link;
}
Future<dynamic> post(dynamic body) async {
String _baseUrl = "https://html2json.com/api/v1";
var options = Options(
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
followRedirects: false,
);
final response = await dio.post(
_baseUrl,
data: body,
options: options,
);
return response;
}
FloatingActionButton(
onPressed: () async {
dynamic responseHTML = await test();
response = await post(responseHTML.data); //This will contain the JSON response
},
);

The getter 'length' was called on null in post request

I'm trying to make a post request to an API, and I couldn't get why this is happening.
This is my code:
print('THIS IS PRINTING');
var response = await http.post(url, body: body, headers: header);
print('This not printing (throwing error before it prints)');
This is the error that I'm getting:
I/flutter ( 2417): NoSuchMethodError: The getter 'length' was called on null.
I/flutter ( 2417): Receiver: null
I/flutter ( 2417): Tried calling: length
I'm able to make the request using PostMan, and giving the same fields and values, I get this error on dart. I'm also able to make other get requests without any issues.
Full code:
void getFavorites() async {
var url = "https://www.my-url-edited.com/favorite";
var header = {
"Content-Type": "application/x-www-form-urlencoded",
"token": "my token ---- edited",
};
var body = {
"car_id": "1",
"boat_id": null,
"habitation_id": null,
"product_id": null,
};
try {
print('print before post request --- working');
// var response = await http.post(url, body: body, headers: header);
var response = await http.post(url, body: body, headers: header);
print('This not printing (throwing error before it prints)');
print(response.body);
// var data = json.decode(response.body);
} catch (e) {
print(e);
throw Exception('Not connected to network');
}
}
you header should be ,
headers: {'Content-type': 'application/json','Accept': 'application/json'}
Try
var header = {
"Content-Type": "application/json",
"token": "my token ---- edited",
};
var body = jsonEncode({
"car_id": "1",
});

How to fix errors on http put request on flutter

I'm trying to authenticate using the below code and unable to succeed. It looks like the json structure is incorrect.
I've tried to check the same on native android using kotlin and it works correctly.
below are the logs
flutter: {data: {email: nelloresec#xxx.com, password: xxx}}
flutter: "{\"errors\":[]}"
flutter: http://xxx.xxx.xx
flutter: Instance of 'Response'
flutter: 400
flutter: {errors: []}
The default content-type for a body of types String, List<int> or Map<String, String> is 'text/plain' and I guess you want 'application/json'
In addition you can directly pass in the user object to the body paramater (as toJson will be invoked automatically by the json.encode()-function).
Lastly, you don't need to use both await and .then(...), await will suffice:
void userLogin(String url, User user) async {
http.Response response = await http.put(
'$url/api/login',
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
},
body: json.encode(user),
);
if (response.statusCode == 200) {
print(url);
print(response.statusCode);
print(json.decode(response.body));
} else {
print(json.encode(response.body));
print(url);
print(response);
print(response.statusCode);
print(json.decode(response.body));
throw Exception("Error while fetching data");
}
}