2

我正在尝试使用 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 应该只包含内容类型标题。

如何使用 System.Net.Http 库创建和发送 POST 请求,在其中设置 Content-Type 标头、授权标头并在正文中包含 Json?

4

1 回答 1

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对象中。

于 2015-06-25T12:42:16.783 回答