Uncle Vector
Uncle Vector

Reputation: 381

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

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

Upvotes: 7

Views: 25295

Answers (2)

janstol
janstol

Reputation: 3157

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.

Upvotes: 17

alhussien aldali
alhussien aldali

Reputation: 139

String url =
    'http://wwww.foo.com';
http.get(url).then((http.Response response) {
  is_loading=true;
  // print(json.decode(response.body));

  Map<String, dynamic> Data = json.decode(response.body);
  Data.forEach((String data, dynamic data_value) {
    print(data + " : ");
    print(data_value.toString());
    //  Map<String,String> decoded_data=json.decode(data);
    //  print(data_value.toString());
    //print(data['title']);
    //print(data['content']);
  });

Upvotes: -1

Related Questions