I have a Rest API successfully running and can make curl post as:
curl -X POST "{{baseURL}}/api/auth/login" -H "accept: application/json" -H "Content-Type: application/json-patch+json" -d "{ \"nick\": \"string"\", \"password\": \"string\"}"
My wish is to write a code that will do the exact job as above command, I mean how to decode/encode stuff in proper way. This is what I got so far:
Future<http.Response> postRequest (String nick, String password) async {
var url ='{{baseURL}}/api/auth/login';
var body = jsonEncode({ "nick": "$nick", "password": "$password"});
print("Body: " + body);
http.post(url,
headers: {"accept": "application/json","Content-Type": "application/json-
patch+json"},
body: body
).then((http.Response response) {
});
}
Thanks!
There's no need to use then
inside an async
function - it's typically easier and more readable to use await
. I assume you don't really want to return the Response
and leave it to the caller to handle that. Since your accept is set to JSON, you may as well immediately decode the response and return the parsed tree (or some part of it) - but only a suggestion.
(I've corrected style and formatting a bit.)
Try this:
Future<Map<String, dynamic>> postRequest(String nick, String password) async {
// todo - fix baseUrl
var url = '{{baseURL}}/api/auth/login';
var body = json.encode({
'nick': nick,
'password': password,
});
print('Body: $body');
var response = await http.post(
url,
headers: {
'accept': 'application/json',
'Content-Type': 'application/json-patch+json',
},
body: body,
);
// todo - handle non-200 status code, etc
return json.decode(response.body);
}
var map = new Map<String, dynamic>();
map["nick"] = nick;
map["password"] = password;
http.post(url, body: map);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With