我正在尝试使用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请求,在该请求中,我可以使用System.Net.Http库设置Content-Type标头、Authorization标头,并在正文中包含Json?
我使用下面的代码来构建我的请求:
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
对象。