2015-06-23 24 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对象。