105

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);

Community
  • 1
  • 1
user2970840
  • 1,231
  • 2
  • 9
  • 13
  • Did you try to use the Post method? – Patrick Nov 15 '13 at 16:16
  • You should follow the documentation for what content you should send in your post (if you are following an API). Then, just fill a HttpContent and use [PostAsync](http://msdn.microsoft.com/en-us/library/hh138190(v=vs.110).aspx) did you try that? – Patrick Nov 15 '13 at 16:24
  • 5
    Btw, posting comments 10 minutes after posting your question with "can't anyone help?" and a smiley face will probably not encourage other overflowers to help you faster. If you don't find anyone answering your question you might want to look at your question and see what you can do to improve it, with more information about what you tried, instead of expecting everyone else to guess what you know. – Patrick Nov 15 '13 at 16:28
  • @Patrick ok, I have updated it. please see if that is enough. – user2970840 Nov 15 '13 at 16:31
  • 1
    If someone is looking to upload a file using HttpClient - [C# HttpClient 4.5 multipart/form-data upload](https://stackoverflow.com/q/16416601/465053) – RBT Sep 26 '19 at 08:59

3 Answers3

216

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();
starball
  • 20,030
  • 7
  • 43
  • 238
Icaro Bombonato
  • 3,742
  • 1
  • 17
  • 12
  • response is `Unprocessable entry`. maybe I have a mistake somewhere else – user2970840 Nov 15 '13 at 17:03
  • 18
    or shorter dictionary literal: `var formContent = new FormUrlEncodedContent(new Dictionary { {"comment", comment}, {"questionId", questionId } });` – hkarask Feb 10 '17 at 14:30
  • Related post - [POSTing JsonObject With HttpClient From Web API](https://stackoverflow.com/q/6117101/465053) – RBT Sep 07 '21 at 04:21
8

Try to use this:

using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
{
    using (var client = new HttpClient(handler) { BaseAddress = new Uri("site.com") })
    {
        //add parameters on request
        var body = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("test", "test"),
            new KeyValuePair<string, string>("test1", "test1")
        };

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "site.com");

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded; charset=UTF-8"));
        client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
        client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
        client.DefaultRequestHeaders.Add("X-MicrosoftAjax", "Delta=true");
        //client.DefaultRequestHeaders.Add("Accept", "*/*");

        client.Timeout = TimeSpan.FromMilliseconds(10000);

        var res = await client.PostAsync("", new FormUrlEncodedContent(body));

        if (res.IsSuccessStatusCode)
        {
            var exec = await res.Content.ReadAsStringAsync();
            Console.WriteLine(exec);
        }                    
    }
}
poke
  • 369,085
  • 72
  • 557
  • 602
L.Zoffoli
  • 129
  • 3
  • 10
  • 3
    You may want to use MultipartFormDataContent instead of FormUrlEncodedContent (that depends on what your server expects) – ed22 May 09 '21 at 10:53
-2

Use UploadStringAsync method:

WebClient webClient = new WebClient();
webClient.UploadStringCompleted += (s, e) =>
{
    if (e.Error != null)
    {
        //handle your error here
    }
    else
    {
        //post was successful, so do what you need to do here
    }
};

webClient.UploadStringAsync(new Uri(yourUri), UriKind.Absolute), "POST", yourParameters);     
poke
  • 369,085
  • 72
  • 557
  • 602