Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Dart - How to send a Post Request using HttpClient()

Tags:

http

flutter

dart

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

like image 916
Uncle Vector Avatar asked Oct 05 '19 11:10

Uncle Vector


People also ask

How do you send data in body of post request in flutter?

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.

What is post method in flutter?

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.


1 Answers

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.

like image 74
janstol Avatar answered Oct 17 '22 01:10

janstol