How to post data using HttpClient?

149,240

Solution 1

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

Solution 2

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);
        }                    
    }
}
Share:
149,240

Related videos on Youtube

user2970840
Author by

user2970840

Updated on April 07, 2020

Comments

  • user2970840
    user2970840 about 4 years

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

    • Patrick
      Patrick over 10 years
      Did you try to use the Post method?
    • Patrick
      Patrick over 10 years
      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 did you try that?
    • user2970840
      user2970840 over 10 years
      @Patrick thanks, I have updated my question
    • Patrick
      Patrick over 10 years
      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.
    • user2970840
      user2970840 over 10 years
      @Patrick ok, I have updated it. please see if that is enough.
    • RBT
      RBT over 4 years
      If someone is looking to upload a file using HttpClient - C# HttpClient 4.5 multipart/form-data upload
  • user2970840
    user2970840 over 10 years
    thanks, but I think this HttpClient is better than WebClient. easier and cleaner. isn't it?
  • user2970840
    user2970840 over 10 years
    response is Unprocessable entry. maybe I have a mistake somewhere else
  • Lori Lalonde - MSFT
    Lori Lalonde - MSFT over 10 years
    Ah yes, I'm so used to WebClient, I had that in my head when I was reading the question. I haven't used HttpClient as of yet. Sorry!
  • hkarask
    hkarask about 7 years
    or shorter dictionary literal: var formContent = new FormUrlEncodedContent(new Dictionary<string, string> { {"comment", comment}, {"questionId", questionId } });
  • ed22
    ed22 about 3 years
    You may want to use MultipartFormDataContent instead of FormUrlEncodedContent (that depends on what your server expects)
  • RBT
    RBT over 2 years