2015-06-23 21 views
2

我想使用的Zendesk的票提交API及其文檔中,他們給的捲曲下面的例子:如何使用System.Net.Http發送下面顯示的cURL請求?

curl https://{subdomain}.zendesk.com/api/v2/tickets.json \ -d '{"ticket": {"requester": {"name": "The Customer", "email": "[email protected]"}, "subject": "My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}}' \ -H "Content-Type: application/json" -v -u {email_address}:{password} -X POST

我試圖讓使用System.Net.Http庫這個POST請求:

var httpClient = new HttpClient(); 
HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(model)); 
if (httpContent.Headers.Any(r => r.Key == "Content-Type")) 
    httpContent.Headers.Remove("Content-Type"); 
httpContent.Headers.Add("Content-Type", "application/json"); 
httpContent.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String(Encoding.ASCII.GetBytes("{user}:{password}")))); 
var httpResult = httpClient.PostAsync(WebConfigAppSettings.ZendeskTicket, httpContent); 

我在嘗試將授權標頭添加到內容時不斷收到錯誤。我現在明白HttpContent只應該包含內容類型標題。

如何創建和發送POST請求,我可以使用System.Net.Http庫設置Content-Type標頭,Authorization標頭以及在主體中包含Json?

回答

1

我用下面的代碼來構建我的請求:

HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(new { ticket = model })); 
if (httpContent.Headers.Any(r => r.Key == "Content-Type")) 
    httpContent.Headers.Remove("Content-Type"); 
httpContent.Headers.Add("Content-Type", "application/json"); 
var httpRequest = new HttpRequestMessage() 
{ 
    RequestUri = new Uri(WebConfigAppSettings.ZendeskTicket), 
    Method = HttpMethod.Post, 
    Content = httpContent 
}; 
httpRequest.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(@"{username}:{password}")))); 
httpResult = httpClient.SendAsync(httpRequest); 

基本上,我建立與內容分開加入所述主體和設置報頭。然後我將驗證頭添加到httpRequest對象。所以我不得不將內容頭添加到httpContent對象,並將授權頭添加到httpRequest對象。