简体   繁体   English

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

[英]How to post JSON with HttpClient using C#?

I have no idea how to POST JSON with HttpClient. 我不知道如何使用HttpClient POST JSON。 I find some solution, like this , but I have to use HttpClient, cause of async and have to add a header. 我找到了一些解决方案, 像这样 ,但我必须使用HttpClient,导致异步并且必须添加标头。

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

You can use the method PostAsJsonAsync which can be found in the extensions assemblies: 您可以使用可在扩展程序集中找到的PostAsJsonAsync方法:

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 : 如果要向请求添加自定义标头,请将其添加到DefaultRequestHeaders

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

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;

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM