7

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

3
  • Never flutter or dart before but I imagine client has tuples like client["keep-alive"] = true Commented Oct 5, 2019 at 11:30
  • Which http client are you using? Commented Oct 5, 2019 at 11:45
  • @ChennaReddy built in dart library Commented Oct 5, 2019 at 12:04

2 Answers 2

17

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, so to add post data request.add(data)?
@UncleVector No, request.write(). I added an example to my answer.
-1
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']);
  });

1 Comment

OP wanted to have the solution with HttpClient and you use the http package.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.