Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert cURL to http post in Flutter

Tags:

curl

flutter

dart

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!

like image 750
Firat Avatar asked Jul 03 '19 21:07

Firat


2 Answers

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);
}
like image 56
Richard Heap Avatar answered Sep 24 '22 14:09

Richard Heap


var map = new Map<String, dynamic>();
map["nick"] = nick;
map["password"] = password;
http.post(url, body: map);
like image 20
rstrelba Avatar answered Sep 24 '22 14:09

rstrelba