119

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

5
  • Did you try to use the Post method? Commented Nov 15, 2013 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 did you try that? Commented Nov 15, 2013 at 16:24
  • 6
    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. Commented Nov 15, 2013 at 16:28
  • @Patrick ok, I have updated it. please see if that is enough. Commented Nov 15, 2013 at 16:31
  • 2
    If someone is looking to upload a file using HttpClient - C# HttpClient 4.5 multipart/form-data upload Commented Sep 26, 2019 at 8:59

3 Answers 3

237

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();
Sign up to request clarification or add additional context in comments.

5 Comments

response is Unprocessable entry. maybe I have a mistake somewhere else
or shorter dictionary literal: var formContent = new FormUrlEncodedContent(new Dictionary<string, string> { {"comment", comment}, {"questionId", questionId } });
Thank you for this FormUrlEncodedContent answer! I was trying to do a .PostAsync() with MultiPartFormDataContent and got a response that it couldn't be parsed as Form Data.
@D.Ror. That makes sense, as FormUrlEncodedContent is application/x-www-form-urlencoded content type, while MultipartFormDataContent is multipart/form-data. These are not the same.
9

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

1 Comment

You may want to use MultipartFormDataContent instead of FormUrlEncodedContent (that depends on what your server expects)
-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);     

2 Comments

thanks, but I think this HttpClient is better than WebClient. easier and cleaner. isn't it?
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!

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.