如何使用System.Net.Http发送下面显示的cURL请求?

时间:2015-06-23 19:18:08

标签: c# http curl http-headers zendesk

我正在尝试使用Zendesk的票证提交API,在他们的文档中,他们在cURL中给出了以下示例:

curl https://{subdomain}.zendesk.com/api/v2/tickets.json \ -d '{"ticket": {"requester": {"name": "The Customer", "email": "thecustomer@domain.com"}, "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);

当我尝试将Authorization标头添加到内容时,我一直收到错误消息。我现在明白HttpContent只应包含内容类型标题。

如何创建和发送POST请求,我可以在其中设置Content-Type标头,Authorization标头,并使用System.Net.Http库在主体中包含Json?

1 个答案:

答案 0 :(得分: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对象。