2

I'm relatively new to flutter. I'm trying to make an API call using the flutter HTTP package (along with header and body)

For example, how could I make the same call in Flutter HTTP?

curl --location --request POST 'xyz.com' \
--header 'Referer: {{your app package name or website url}}' \
--header 'API-KEY: {{api-key}}' \
--data-urlencode 'vehicleId=MHxxxxxxxx' // how to pass this in http body

This is what I could do so far, am I doing it correctly so far? How can I pass body content?

Map<String, String> headers = {"Referer": "abcd.com", "API-KEY": "abcd12345"};
 var url = Uri.parse('xyz.com');
 var response = await post(url, headers: headers);
shakky
  • 434
  • 5
  • 20
  • `Future createAlbum(String title) { return http.post( Uri.parse('https://jsonplaceholder.typicode.com/albums'), headers: { 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode({ 'title': title, }), ); }` – Anmol Mishra Dec 15 '21 at 17:29
  • `await post(url, headers: headers, body: {'vehicleid': 'MHxxxxxx'});` is this what you want? Sorry not super familiar with Curl. I don't know what `--data-urlencode` does – h8moss Dec 15 '21 at 17:30
  • `https://docs.flutter.dev/cookbook/networking/send-data` – Anmol Mishra Dec 15 '21 at 17:30
  • Same here! This is what confuses me (--data-urlencode), the API sample response was given to me by the API provider, so I'm not sure if this is the right way to do it body: {'vehicleid': 'MHxxxxxx'}) @h8moss – shakky Dec 15 '21 at 17:35
  • you may say why don't you test it but the API provider won't give me authorization to API data until I integrate it into my application, so can't test it @h8moss – shakky Dec 15 '21 at 17:38
  • After reading [this](https://curl.se/docs/manpage.html#--data-urlencode) I believe this is a more correct way to do what you want: `body: Uri.encodeComponent('vehicleId=MHxxxxxxxx')` but again I am not very familiar with cUrl – h8moss Dec 15 '21 at 17:47
  • no problem! thank you for your help! appreciate it @h8moss – shakky Dec 15 '21 at 18:19

1 Answers1

2

to create a header for HTTP call, you can do it this way. Hope its help you.

  Map<String, String> _header = <String, String>{
      "Referer": "abcd.com", 
      "API-KEY": "abcd12345"
  };

  final response = await http.post(
      Uri.parse(url),
      headers: _header,
      body: data
  );
Ananda Pramono
  • 899
  • 1
  • 6
  • 18