C# - Body content in POST request

Step 1. Choose a type that derives from HttpContent. If you want to write a lot of content with runtime code, you could use a StreamContent and open some sort of StreamWriter on it. For something short, use StringContent. You can also derive your own class for custom content.

Step 2. Pass the content in a call to HttpClient.PostAsync.

Here's an example that uses StringContent to pass some JSON:

string json = JsonConvert.SerializeObject(someObject);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var httpResponse = await httpClient.PostAsync("http://www.foo.bar", httpContent);

See also How do I set up HttpContent?.


Thanks to this and this, I finally found the solution to send post requests with headers AND body content. Here's the code:

        var cl = new HttpClient();
        cl.BaseAddress = new Uri("< YOUR URL >");
        int _TimeoutSec = 90;
        cl.Timeout = new TimeSpan(0, 0, _TimeoutSec);
        string _ContentType = "application/x-www-form-urlencoded";
        cl.DefaultRequestHeaders.Add(key, value);
        cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
        cl.DefaultRequestHeaders.Add("key", "value");
        cl.DefaultRequestHeaders.Add("key", "value");
        var _UserAgent = "d-fens HttpClient";
        cl.DefaultRequestHeaders.Add("User-Agent", _UserAgent);

        var nvc = new List<KeyValuePair<string, string>>();
        nvc.Add(new KeyValuePair<string, string>("key of content", "value"));
        var req = new HttpRequestMessage(HttpMethod.Post, "http://www.t-lab.fr:3000/add_tips") { Content = new FormUrlEncodedContent(nvc) };
        var res = cl.SendAsync(req);