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);
An HTTP POST request can be sent to add new data in the API server using the SendJsonAsync () method provided by the HttpClient class.
Using SendAsync, we can write the code as: static async Task SendURI(Uri u, HttpContent c) { var response = string. Empty; using (var client = new HttpClient()) { HttpRequestMessage request = new HttpRequestMessage { Method = HttpMethod. Post, RequestUri = u, Content = c }; HttpResponseMessage result = await client.
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 ;)
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); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With