如何使用C#发布带有HttpClient的JSON?

时间:2015-02-12 02:54:49

标签: c# json asynchttpclient

我不知道如何使用HttpClient POST JSON。我找到了一些解决方案,like this,但我必须使用HttpClient,因为异步并且必须添加标题。

这是我的代码如下。知道怎么解决吗?

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

2 个答案:

答案 0 :(得分:9)

您可以使用扩展程序集中可以找到的方法PostAsJsonAsync

System.Net.Http.Formatting.dll

实施例

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

如果您要为请求添加自定义标头,请将其添加到DefaultRequestHeaders

client.DefaultRequestHeaders.Add("mycustom", "header1");

答案 1 :(得分:0)

您可以发送任何类型的请求,例如

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;

        }