How to post data using HttpClient?

2020-01-24 22:39发布

问题:

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

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



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


回答3:

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