Calling REST service from C# code

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.


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";

我建议使用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);
链接地址: http://www.djcxy.com/p/45884.html

上一篇: 在Asp.Net中调用REST API

下一篇: 从C#代码调用REST服务