I am using the following code to call a REST service using C#
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())
{
....
}
}
And I am getting an exception "400 bad request" on the line calling GetResponse()
. The documentation of the service says the status code 400 means a required argument is missing. But as you can see the argument name
(which is the only required argument ) is supplied with the request.
I tried to call the service with CURL and it successfully got executed.
curl -v -b cookie.txt -X POST -H "Content-Type: application/json" -d "{\"name\": \"TestName\"}" http://something.com:1234/content/abc.v1.json
So I assume there is something wrong with my C# code which doesn't seem to be passing the parameters. Any idea?
EDIT
Here is the relevant part of the documentation:
Method
POST
Headers
Content-Type: application/json
Body
The request body is made up of JSON containing the following properties:
Name : name Required : yes Type: string
Response Status codes
201 Created Success
400 Bad Request A required property is missing in the request body.