使用HttpClient和C#发送Post请求时发送一个JSON。

5

我遇到了一个问题,我的目标是通过API发送修改请求,所以我正在使用HttpClient进行request

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

public class patchticket
{
   public string patch(string ticketid)
   {

       using (var httpClient = new HttpClient())
       {
           using (var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://desk.zoho.com/api/v1/tickets/"+ticketid))
           {
               request.Headers.TryAddWithoutValidation("Authorization", "6af7d2d213a3ba5e9bc64b80e02b000");
               request.Headers.TryAddWithoutValidation("OrgId", "671437200");

               request.Content = new StringContent("{\"priority\" : \"High\"}", Encoding.UTF8, "application/x-www-form-urlencoded");


               var response =  httpClient.SendAsync(request);
           return response

           }
       }

   }
}

结果是我没有任何错误,但是更改没有生效。
认证凭据没问题,我已经使用相同的参数通过curl测试过,它很好地工作了。

你是不是想说“PATCH”而不是“PATH”?另外,由于你已经在这里暴露了API凭据,现在需要更改它们。 - CodeCaster
抱歉,是PATCH请求,那些凭据是错误的 ;) - user11110224
1个回答

10
看起来你想在请求中发布一个 JSON。试着定义正确的内容类型,即 application/json。例如:
request.Content = new StringContent("{\"priority\" : \"High\"}",
                                    Encoding.UTF8, 
                                    "application/json");

由于您的方法返回一个字符串,它可以是一个非异步方法。方法SendAsync是异步的,您必须等待请求完成。您可以尝试在请求之后调用Result。示例代码如下:
var response = httpClient.SendAsync(request).Result;
return response.Content; // string content

你将会得到一个 HttpResponseMessage 对象。它包含了关于响应的许多有用信息。
无论如何,由于这是一个IO绑定的操作,最好使用异步版本,像这样:
var response = await httpClient.SendAsync(request);
return response.Content; // string content

好的,我明天再试一下,谢谢。你认为这就是问题所在吗?之前我使用的是 var response = await httpClient.SendAsync(request); 但是出现了一个带有 await 的错误提示,说我不能使用它,你知道为什么吗? - user11110224
好的,我明天尝试一下 :) - user11110224

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接