2015-02-12 97 views
5

我不知道如何發佈JSON與HttpClient的,如何使用HttpClient發佈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(); 

回答

7

您可以使用該方法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");