How to post data using HttpClient?

user2970840 picture user2970840 · Nov 15, 2013 · Viewed 112.7k times · Source

I have got this HttpClient from Nuget.

When I want to get data I do it this way:

var response = await httpClient.GetAsync(url);
var data = await response.Content.ReadAsStringAsync();

But the problem is that I don't know how to post data? I have to send a post request and send these values inside it: comment="hello world" and questionId = 1. these can be a class's properties, I don't know.

Update I don't know how to add those values to HttpContent as post method needs it. httClient.Post(string, HttpContent);

Answer

Icaro Bombonato picture Icaro Bombonato · Nov 15, 2013

You need to use:

await client.PostAsync(uri, content);

Something like that:

var comment = "hello world";
var questionId = 1;

var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("comment", comment), 
    new KeyValuePair<string, string>("questionId", questionId) 
});

var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);

And if you need to get the response after post, you should use:

var stringContent = await response.Content.ReadAsStringAsync();

Hope it helps ;)