我使用以下代码使用C#
调用REST服务 string PostData= @"{""name"":""TestName""}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://something.com:1234/content/abc.v1.json");
request.Method = "POST";
request.ContentLength = 0;
request.ContentType = ContentType;
request.Accept = "application/json";
request.KeepAlive = false;
request.CookieContainer = cookie;
if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
request.ContentLength = bytes.Length;
request.AllowAutoRedirect = true;
using (Stream writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
}
try
{ // Gets exception
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
....
}
}
我在调用GetResponse()
的行上收到异常“400错误请求”。该服务的文档说状态代码400表示缺少必需的参数。但正如您所看到的那样,请求提供了参数name
(这是唯一必需的参数)。
我尝试用CURL调用该服务并成功执行。
curl -v -b cookie.txt -X POST -H“Content-Type:application / json”-d “{\”name \“:\”TestName \“}” http://something.com:1234/content/abc.v1.json
所以我认为我的C#代码有些问题似乎没有传递参数。有什么想法吗?
修改
以下是文档的相关部分:
方式
POST
接头
内容类型: application / json
车身
请求正文由包含以下属性的JSON组成:
名称:名称必填:是类型:字符串
响应 状态代码
201创造成功
400 Bad Request请求正文中缺少必需的属性。
答案 0 :(得分:1)
这不是POST请求中数据的发送方式。它应该是这样的:
string PostData= "name=TestName";
如果您有多个值,请将它们与&
字符分开。例如:
string PostData= "name=TestName&number=20";
答案 1 :(得分:0)
我建议使用System.Net.Http HttpClient类。
string PostData = @"{""name"":""TestName""}";
var httpClientHandler = new HttpClientHandler();
httpClientHandler.CookieContainer = cookies;
var httpClient = new HttpClient(httpClientHandler);
var content = new StringContent(PostData,
Encoding.GetEncoding("iso-8859-1"), "application/json");
httpClient.PostAsync("http://something.com:1234/content/abc.v1.json", content);