Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post JSON with HttpClient using C#?

I have no idea how to POST JSON with HttpClient. I find some solution, like this, but I have to use HttpClient, cause of async and have to add a header.

This is my code below. Any idea how to fix it?

List<Order> list = new List<Order> { new Order() { Name = "CreatedTime", OrderBy = 1 } };

Queues items = new Queues { Orders = list };

var values = new Dictionary<string, string> { { "Orders", JsonConvert.SerializeObject(list) } };

var content = new FormUrlEncodedContent(values);

//HttpContent cc = new StringContent(JsonConvert.SerializeObject(items));

_msg = await _client.PostAsync(input, content);

//_msg = await _client.PostAsync(input, cc);

var response = await _msg.Content.ReadAsStringAsync();
like image 942
Louis Avatar asked Feb 12 '15 02:02

Louis


People also ask

How do I post JSON data to API using C #?

To post JSON to a REST API endpoint using C#/. NET, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the C#/. NET POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

How do I use HttpClient Getasync?

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.


2 Answers

You can use the method PostAsJsonAsync which can be found in the extensions assemblies:

System.Net.Http.Formatting.dll

Example

public static async Task SendJsonDemo(object content)
{
    using(var client = new HttpClient())
    {
        var response = await client.PostAsJsonAsync("https://example.com", content);
    }
}

If you want to add custom headers to the request, add it to DefaultRequestHeaders:

client.DefaultRequestHeaders.Add("mycustom", "header1");
like image 125
Peter Mols Avatar answered Oct 10 '22 21:10

Peter Mols


You can send any type of request like as

public static async Task<HttpResponseMessage> SendRequest(HttpMethod method, string endPoint, string accessToken,  dynamic content = null)
        {
            HttpResponseMessage response = null;
            using (var client = new HttpClient())
            {
                using (var request = new HttpRequestMessage(method, endPoint))
                {
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    if (content != null)
                    {
                        string c;
                        if (content is string)
                            c = content;
                        else
                            c = JsonConvert.SerializeObject(content);
                        request.Content = new StringContent(c, Encoding.UTF8, "application/json");
                    }

                    response = await client.SendAsync(request).ConfigureAwait(false);
                }
            }
            return response;

        }
like image 36
Md. Abdul Alim Avatar answered Oct 10 '22 20:10

Md. Abdul Alim