如何使用HttpClient发布JSON?
我不知道如何使用HttpClient发布JSON,
我找到一些解决方案,
喜欢这个
但我必须使用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();
您可以使用可在扩展程序集中找到的方法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");
链接地址: http://www.djcxy.com/p/45875.html