我花了几周时间尝试从C#向API发出POST请求,但没有成功。官方文档提供的示例如下:
curl -v -u MYTOKEN:api_token \
-H "Content-Type: application/json" \
-d '{"object":{"param1":"a","param2":2,"param3":3,"param4":true,"param5":5}}' \
-X POST APIURL
这是我目前正在尝试执行请求的方式
var webAddr = "APIURL";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Credentials = new NetworkCredential("MYTOKEN", "api_token");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"object\":{\"param1\":\"a\",\"param2\":2,\"param3\":3,\"param4\":true,\"param5\":5}}";
streamWriter.Write(json);
streamWriter.Flush();
}
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
}
catch(Exception e)
{
Console.WriteLine(e);
}
我已经在Linux终端中使用CURL测试了请求,它运行正常,所以这不是问题。
我得到的错误是403“禁止”。文档说明凭证将与令牌一起用作用户名,“api_token”用作密码。
谢谢!