I am trying to send a Post request to my server using HttpClient
but I am not sure where to actually set the payload and headers that need to be sent.
var client = new HttpClient();
client.post(host, port, path);
client.post(host, port, path)
has only 3 arguments so how do I set the payload to be sent?
Thanks in advance
flutter Share on : If you want to send form data in HTTP post request in Flutter or Dart, you can use map and add data to it and pass the map variable to the body parameter of http. post() function.
Flutter HTTP POST request method is used to fetch the values from the api based on user provided input which means when you are trying to find out the result of a exam you will provide a hall ticket number as input parameter.
post() opens a HTTP connection using the POST method and returns Future<HttpClientRequest>
.
So you need to do this:
final client = HttpClient();
final request = await client.post(host, port, path);
request.headers.set(HttpHeaders.contentTypeHeader, "plain/text"); // or headers.add()
final response = await request.close();
Example with jsonplaceholder:
final client = HttpClient();
final request = await client.postUrl(Uri.parse("https://jsonplaceholder.typicode.com/posts"));
request.headers.set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
request.write('{"title": "Foo","body": "Bar", "userId": 99}');
final response = await request.close();
response.transform(utf8.decoder).listen((contents) {
print(contents);
});
prints
{
"title": "Foo",
"body": "Bar",
"userId": 99,
"id": 101
}
Or you can use http library.
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