How to convert cURL to http post in Flutter

7,287

Solution 1

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

Solution 2

var map = new Map<String, dynamic>();
map["nick"] = nick;
map["password"] = password;
http.post(url, body: map);
Share:
7,287
Firat
Author by

Firat

Computer Science and Engineering student.

Updated on December 12, 2022

Comments

  • Firat
    Firat over 1 year

    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!

  • Firat
    Firat almost 5 years
    Thanks Richard! You saved my day :)
  • Firat
    Firat almost 5 years
    Thanks for your answer!