What's the best way to consume secure REST web service in C#? Web Service username and password are supplied in URL...
Several options:
HttpWebRequest class. Powerful but sometimes complex to use.
WebClient class. Less features, but should work for simpler web services, and much simpler.
The new HttpClient in the WCF REST Starter Kit. (The Starter Kit is a separate download, not a part of the .NET Framework).
Use WebRequest class to make the request and HttpWebResponse to get the response.
I used following code for consuming webservice.My user name,password and Url are saved in variables UserName,Pwd and Url respectively.
WebRequest Webrequest;
HttpWebResponse response;
Webrequest = WebRequest.Create(Url);
byte[] auth1 = Encoding.UTF8.GetBytes(UserName + ":" + Pwd);
Webrequest.Headers["Authorization"] = "Basic " + System.Convert.ToBase64String(auth1);
Webrequest.Method = "GET";
Webrequest.ContentType = "application/atom+xml";
response = (HttpWebResponse)Webrequest.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
string Response = streamReader.ReadToEnd();
Response string will be available in variable Response.
I hope the password in the URL is somwhow encrypted :). Maybe this will help you:
http://social.msdn.microsoft.com/forums/en-US/wcf/thread/3c8db0bf-984e-426b-b068-d80165ed1b37/
Based on the little information you provided I would say that using the HttpWebRequest class is your best option.
It is relatively easy to use, there are lots of examples of how to use it and it will work with any media-type the REST interface delivers. You have full access to Http status codes, and Http Headers.
What more can you ask for?
Related
I am new to StackOverflow but I heard that there are awesome and helpful people who can help me out. 😉
My mission:
To find a way to make a trade calling the Binance REST API using c#
Without dlls, using my own code (for speed update)
Now I using the Binance.API package but my bot needs to be a bit faster as its speed is not enough.
Also, it would be a great thing to be able to do that without any external sources like dlls. Isn't it? 😎
What I tried:
Success: I can call the public API without problem with "WebRequest" and which there is no need authentication.
WebRequest webrequest = WebRequest.Create("https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT");
WebResponse Response = webrequest.GetResponse();
StreamReader reader = new StreamReader(Response.GetResponseStream());
MessageBox.Show(reader.ReadToEnd());
Success: I can call the REST API without problem with "WebRequest" and which there is need authentication. BUT only the account information.
string dataQueryString = "recvWindow=15000×tamp=" + Math.Round(Convert.ToDecimal(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds), 0).ToString();
WebRequest webrequest = WebRequest.Create("https://api.binance.com/api/v3/account?" + dataQueryString + "&signature=" + BitConverter.ToString(new HMACSHA256(Encoding.ASCII.GetBytes(tempAPI_Secret)).ComputeHash(Encoding.ASCII.GetBytes(dataQueryString))).Replace("-", string.Empty).ToLower());
webrequest.Method = "GET";
webrequest.Headers.Add("X-MBX-APIKEY", tempAPI_Key);
WebResponse Response = webrequest.GetResponse();
StreamReader reader = new StreamReader(Response.GetResponseStream());
string response = reader.ReadToEnd();
reader.Close();
Response.Close();
!!! THE PROBLEM !!! I can't call the ORDER REST API with "WebRequest" and which there is need authentication. I tried the code below. (It is called the same way as the account information but with the type of POST and of course with the plus parameters needed)
string dataQueryString = "symbol=BTCUSDT&side=SELL&type=LIMIT&quantity=0.00039&price=38878&newOrderRespType=RESULT&recvWindow=15000×tamp=" + Math.Round(Convert.ToDecimal(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds), 0).ToString();
WebRequest webrequest = WebRequest.Create("https://api.binance.com/api/v3/account?" + dataQueryString + "&signature=" + BitConverter.ToString(new HMACSHA256(Encoding.ASCII.GetBytes(tempAPI_Secret)).ComputeHash(Encoding.ASCII.GetBytes(dataQueryString))).Replace("-", string.Empty).ToLower());
webrequest.Method = "POST";
webrequest.Headers.Add("X-MBX-APIKEY", tempAPI_Key);
WebResponse Response = webrequest.GetResponse();
StreamReader reader = new StreamReader(Response.GetResponseStream());
string response = reader.ReadToEnd();
reader.Close();
Response.Close();
The returned ERROR code:
'The remote server returned an error: (400) Bad Request.'
I can't understand why this is not working. (I tried to do the order with exactly these parameters from the web client manually and it was successful)
I checked these possible problems:
I have enough funds on my spot account
I trying to sell more than the minimum trade amount is
There is the official Binance REST API documentation: HERE
I tried to google it but I couldn't find the solution even here.
Thanks to read it and if you could help me I would really appreciate it. 🙏
If something is not clear please ask it, I will answer!
I was literarly doing the same thing you are a few days ago, except I was using python. I'm also glad to see I'm not the only one who likes coding from scratch.
My solution was to leave the url as is https://api.binance.com/api/v3/account and instead of attaching my order parameters symbol=BTCUSD&side=BUY&etc... onto the url I had to instead encode and send that data through the data parameter of python's built in function urllib.request.Request(url, data, headers)
I don't know C# that well so I wouldn't know how to translate my python code to C#, but I did find this doc link that provides an example on how to send data using a POST request. You could also take a look at my question and answer as another example.
I have little problem that I have been trying to solve for some time. I want to connect to a REST web service and I have the API key for that web service that I want to consume. I have tried the service in the Google REST console and it works fine.
But when I try to build a c# .net project for it I dont know how to set the api key for the authentication. I took this code from other site:
string url = "http://Demo.company.com/Data/Values/1029/CarPart/id/"
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(url);
GETRequest.Method = "GET";
Console.WriteLine("Sending GET Request");
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
Stream GETResponseStream = GETResponse.GetResponseStream();
StreamReader sr = new StreamReader(GETResponseStream);
Console.WriteLine("Response from Server");
Console.WriteLine(sr.ReadToEnd());
How can I authenticate this service with my Api key: asdf1234. I need to add it to my header but how? Can you show me some code example?
Cheers
Thor
You should be able to do something like:
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(url);
GETRequest.Method = "GET";
GETRequest.Headers.Add("api-key", "asdf1234");
Where "api-key" is the name of the header you want to set.
I'm having problems with sending POST request in C# and it seems I misunderstood some HTTP basics. So basically I'm implementing RESTfull service client, which work as follows:
Make POST request with username/password and get token
Use this token in header (Authorization:TOKEN) while making other GET/POST/PUT requests
I use WebRequest to make GET requests (with Authorization header) and it's working. But when I use following code to make PUT requests, service is giving "Authentication failed - not logged in" message back:
String url = String.Format("{0}/{1}", AN_SERVER, app);
WebRequest theRequest = WebRequest.Create(url);
theRequest.Method = "POST";
theRequest.ContentType = "text/x-json";
theRequest.ContentLength = json.Length;
Stream requestStream = theRequest.GetRequestStream();
requestStream.Write(Encoding.ASCII.GetBytes(json), 0, json.Length);
requestStream.Close();
theRequest.Headers.Add("Authorization", authToken);
HttpWebResponse response = (HttpWebResponse)theRequest.GetResponse();
I must be making minor mistake (at least I hope so) while sending POST request. So what am I doing wrong?
Thanks.
Moving Headers before the request steam works (as per AI W's comment), because the request stream is adding the body.
The way webrequest is implemented internally, you need to finish the header before writing body, and once its in stream format, its ready to send.
If you look at the implementation of webrequest in reflector or some such decompiling tool, you'll be able to see the logic.
Hope this helps
I'm trying to send a simple POST request to a REST web service and print the response (code is below, mostly taken from Yahoo! developer documentation and the MSDN code snippets provided with some of the documentation). I would expect the client to send:
Request Method: POST (i.e. I expect $_SERVER['REQUEST_METHOD'] == 'POST' in PHP)
Data: foo=bar (i.e. $_POST['foo'] == 'bar' in PHP)
However, it seems to be sending:
Request Method: FOO=BARPOST
Data: (blank)
I know the API works as I've tested it with clients written in Python and PHP, so I'm pretty sure it must be a problem with my C#. I'm not a .NET programmer by trade so would appreciate any comments/pointers on how to figure out what the problem is - I'm sure it's something trivial but I can't spot it myself.
uri, user and password variables are set earlier in the code - they work fine with GET requests.
request = (HttpWebRequest) WebRequest.Create(uri);
request.Credentials = new NetworkCredential(user, password);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
string postData = "foo=bar";
request.ContentLength = postData.Length;
StreamWriter postStream = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
postStream.Write(postData);
postStream.Close();
response = (HttpWebResponse) request.GetResponse();
The REST API is written in PHP, and the $_POST array is empty on the server when using the C# client.
Eventually found the HttpWebRequest.PreAuthenticate property which seems to solve the problem if the code is edited like so:
request = (HttpWebRequest) WebRequest.Create(uri);
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential(user, password);
request.Method = WebRequestMethods.Http.Post;
From the documentation I presume this forces authentication before the actual POST request is sent. I'm not sure why the class doesn't do this automatically (libraries for other languages make this process transparent, unless you explicitly turn it off), but it has solved the problem for me and may save someone else another 2 days of searching and hair-pulling.
For what it's worth, PreAuthenticate doesn't need to be set for GET requests, only POST, although if you do set it for a GET request everything will still work, but take slightly longer.
In a project I'm invovled in, there is a requirment that the price of certain
stocks will be queryed from some web interface and be displayed in some way.
I know the "query" part of the requirment can be easily implemented using a Perl module like LWP::UserAgent. But for some reason, C# has been chosen as the language to implement the Display part. I don't want to add any IPC (like socket, or indirectly by database) into this tiny project, so my question is there any C# equivalent to the Perl's LWP::UserAgent?
You can use the System.Net.HttpWebRequest object.
It looks something like this:
// Setup the HTTP request.
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");
// This is optional, I'm just demoing this because of the comments receaved.
httpWebRequest.UserAgent = "My Web Crawler";
// Send the HTTP request and get the response.
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (httpWebResponse.StatusCode == HttpStatusCode.OK)
{
// Get the HTML from the httpWebResponse...
Stream responseStream = httpWebResponse.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string html = reader.ReadToEnd();
}
I'm not sure, but are you simply trying to make an HTTP Request? If so, you can use the HttpWebRequest class. Here's an example http://www.csharp-station.com/HowTo/HttpWebFetch.aspx
If you want to simply fetch data from the web, you could use the WebClient class. It seems to be quite good for quick requests.