如何使用C#在HttpClient中发布JSON? [英] How to post JSON with HttpClient using C#?
本文介绍了如何使用C#在HttpClient中发布JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道如何使用HttpClient发布JSON.我找到了一些解决方案,像这样,但是我必须使用HttpClient ,导致异步,并且必须添加标题.
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();
推荐答案
You can use the method PostAsJsonAsync which can be found in the extensions assemblies:
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
:
If you want to add custom headers to the request, add it to DefaultRequestHeaders
:
client.DefaultRequestHeaders.Add("mycustom", "header1");
这篇关于如何使用C#在HttpClient中发布JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文