Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in using WebClient object REST API call using C#

I am trying to POST an order to REST API using the below code:

 string URI = "https://api.myTrade.com/s1/order/" + orderId;
            string myParameters = "symbol=AAPL&duration=day&side=buy&quantity=1&type=limit&price=1";
            Console.Write("Parameters : " + myParameters + "\n");
            using (WebClient wc = new WebClient())
            {
                wc.Headers[HttpRequestHeader.Authorization] = "Bearer " + token
                wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                wc.Headers[HttpRequestHeader.Accept] = "application/json";
                string responsebody = wc.UploadString(URI, myParameters);
                //Console.Write("Output : " + responsebody + " ");
                dynamic dynObj = JsonConvert.DeserializeObject(responsebody);

                return responsebody;
            }

I am getting the following exception:

Input String was not in a correct format.

Any help is greatly appreciated.

like image 662
aceventura Avatar asked Dec 20 '13 14:12

aceventura


People also ask

What can I use instead of WebClient?

The HttpWebRequest class provides a lot of control over the request/response object. However, you should be aware that HttpClient was never designed to be a replacement for WebClient. You should use HttpWebRequest instead of HttpClient whenever you need the additional features that HttpWebRequest provides.

What is the use of WebClient in C#?

The WebClient class provides common methods for sending data to or receiving data from any local, intranet, or Internet resource identified by a URI. The WebClient class uses the WebRequest class to provide access to resources.

Which classes would you use to make REST calls using C#?

Use HttpClient to make REST API calls and other type of requests. Below is the code for making a request. using var client = new HttpClient();


1 Answers

There should be a

?

after the orderId before the parameters' string. Also try URL Encoding

http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode(v=vs.110).aspx

and

http://msdn.microsoft.com/en-us/library/zttxte6w(v=vs.110).aspx

Hope it helps.

like image 102
Stewart Mbofana Avatar answered Sep 30 '22 16:09

Stewart Mbofana