0

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.

Sharun
  • 3,022
  • 6
  • 30
  • 59

2 Answers2

1

That's not how data is sent in a POST request. It should look like this:

string PostData= "name=TestName";

If you have more than one value, you separate them with the & character. Example:

string PostData= "name=TestName&number=20";
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • But the documentation says it should be sent in the json format. and btw, i had already tried the method u suggested and it also resulted in the same exception – Sharun Nov 19 '13 at 13:25
  • I have added the relevant part of the documentation in the questiom – Sharun Nov 19 '13 at 13:32
  • @Sharun: Then it's not really a REST service... Anyway, what's in your `ContentType` variable? Is the response coming with the content type `application/json`? – Guffa Nov 19 '13 at 13:32
  • ContentType="application/json" – Sharun Nov 19 '13 at 13:33
  • @Sharun: You have set the `Accept` header to `application/json` also, is that the content type of the response? – Guffa Nov 19 '13 at 13:35
  • Ya on successful execution, the response should be json data. I am getting the json response using CURL – Sharun Nov 19 '13 at 13:37
  • @Sharun: Do you have the correct value in the `Method` variable, so that the code that sends the post data is executed? – Guffa Nov 19 '13 at 14:06
  • The code execute correctly till `using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())` – Sharun Nov 19 '13 at 14:23
  • @Sharun: Have you verified that the code in the `if` statement actually is executed? There is nothing in there that is needed to send the request, it's only needed to send the correct data in the request. – Guffa Nov 19 '13 at 14:26
  • Ya I checked line by line with the debugger, and checked the content length of request object too, to ensure that the data is there. I think the issue is something else. This code used to work fine for me with normal post, I mean those requests that send data like you said in your answer. – Sharun Nov 19 '13 at 14:30
  • What confuses me is the Curl call works fine with Json data and C# is failing – Sharun Nov 19 '13 at 14:30
  • @Sharun: I can't see anything else wrong with the code. I suggest that you try commenting out all settings that are not essential for the request, where the default values would work, for example the accept, keepalive and cookies. – Guffa Nov 19 '13 at 16:02
0

I suggest using the System.Net.Http HttpClient class.

        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);
Darrel Miller
  • 139,164
  • 32
  • 194
  • 243