Connection time out on REST API call - c#

I have class in c# which makes POST call to a REST API. BUt it gives me a 'connection time out' error with error code as 10060. In the POST call I am trying to make some transaction adjustments in the client's system. When I use Fiddler or Postman to make the api call, the request seems to go through but not from the c# class. Can you see where I am going wrong?
Below is my sample code.
HttpWebRequest request = (HttpWebRequest)WebRequest.CreateHttp(clientURL);
byte[] data = Encoding.UTF8.GetBytes(urlParameters);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream()) **//exception occurs at this point**
{
stream.Write(data, 0, data.Length);
}
Thanks.

You have to close your webrequest by using "using" or adding a call to the HttpWebRequest.Abort() method

The default timeout for HttpWebRequest is 100 seconds. You can change that value by setting that property (in ms):
request.Timeout = 120000;

Related

Microsoft Live custom C# REST API error 415

I'm trying to get data from the Microsoft Live API. However, when I try to get the access_token, I instead get a 415(Unsupported Media Type) error message. I have looked pretty much everywhere, but I can't find any answer (that worked for me).
Here is my (partial) code that tries to get the token (dataToWrite is cut-up for readability, it's one line in the actual code):
WebRequest request;
request = WebRequest.Create("https://login.live.com/oauth20_token.srf");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var dataToWrite = "code=[code]&
client_id=[client_id]&
client_secret=[client_secret]&
redirect_uri=[redirect_uri]&
grant_type=authorization_code";
var buffer = Encoding.ASCII.GetBytes(dataToWrite);
request.ContentLength = buffer.Length;
var dataStream = request.GetRequestStream();
dataStream.Write(buffer, 0, buffer.Length);
dataStream.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
Where the '[]' are:
[code] is a string, given by Microsoft after user logs in (this part of the code works);
[client_id] is a string, given by Microsoft, representing my client id;
[client_secret] is a string, given by Microsoft, representing my client secret;
[redirect_uri] is the URL of the site's return location (same as the URL used in the code for the user consent(see [code]))
According to the manual of Microsoft Live API(http://msdn.microsoft.com/en-us/library/live/hh243647.aspx) this should work. However, the documentation isn't very detailed.
Does anyone know why I keep getting the error?
Thanks!
Never mind, I'm an idiot...
It does work after all. I did another request after this one. And that one failed because I did not include the parameters there.

Is HttpWebRequest.GetResponse required to complete a POST?

For POST requests using HttpWebRequest, when I write to a request stream, at what point does the data get sent? Is it when I close the request stream or when I call GetResponse? Is the GetResponse call required?
The .net documentation does not seem to be very clear about what is really happening
Here's the code I'm curious about:
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentLength = jsonData.Length;
request.ContentType = "application/json";
Stream requestStream = request.GetRequestStream();
requestStream.Write(jsonData, 0, jsonData.Length);
requestStream.Close();
var response = request.GetResponse() as HttpWebResponse;
Thanks!
Yes, GetResponse call is must, not only for POST request but for GET, HEAD requests too. Request / data is sent at the point when you call GetResponse.
Start the sniffer and set breakpoint on your requestStream.Close(); and you will see that request is making when GetResponse() called.

How to post data to a website

I need to post data to a website. So I created a small app in C#.net where I open this website and fill in all the controls (radio buttons, text boxes, checkboxes etc) with the values from my database. I also have a click event on the SUBMIT button. The app then waits for 10-15 seconds and then copies the response from the webpage to my database.
As you can see, this is really a hectic process. If there are thousands of records to upload, this app takes much longer (due to fact that it waits 15s for the response).
Is there any other way to post data? I am looking for something like concatenating all the fields with its value and uploading it like a stream of data. How will this work if the website is https and not http?
You can use HttpWebRequest to do this, and you can concatenate all the values you want to post into a single string for the request. It could look something like this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.yoursite.com");
request.Method = "POST";
formContent = "FormValue1=" + someValue +
"&FormValue2=" + someValue2 +
"&FormValue=" + someValue2;
byte[] byteArray = Encoding.UTF8.GetBytes(formContent);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = HttpUtility.UrlDecode(reader.ReadToEnd());
//You may need HttpUtility.HtmlDecode depending on the response
reader.Close();
dataStream.Close();
response.Close();
This method should work fine for http and https.
MSDN has a great article with step-by-step instructions detailing how you can use the WebRequest class to send data. Link below:
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
Yes, there is a WebClient class. Look into documentation. There're some usful method to make GET and POST requests.

C# REST client sending data using POST

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.

How to read HTTP header from response using .NET HttpWebRequest API?

My app currently uses OAuth to communicate with the Twitter API. Back in December, Twitter upped the rate limit for OAuth to 350 requests per hour. However, I am not seeing this. I am still getting 150 from the account/rate_limit_status method.
I was told that I needed to use the X-RateLimit-Limit HTTP header to get the new rate limit. However, in my code, I do not see that header.
Here is my code...
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newURL);
request.Method = "GET";
request.ServicePoint.Expect100Continue = false;
request.ContentType = "application/x-www-form-urlencoded";
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseString = reader.ReadToEnd();
}
}
If I inspect the response, I can see that it has a property for Headers, and that there are 16 headers. However, I do not have X-RateLimit-Limit in the list.
(source: yfrog.com)
Any idea what I am doing wrong?
You should simple be able to use:
using (WebResponse response = request.GetResponse())
{
string limit = response.Headers["X-RateLimit-Limit"];
...
}
If that doesn't work as expected, you can do a watch on response.Headers and see what's in there.
Look at the raw response text (e.g., with Fiddler). If the header isn't there, no amount of C# code is going to make it appear. :) From what you've shown, it seems the header isn't in the response.
Update: When I go to: http://twitter.com/account/rate_limit_status.xml there is no X-RateLimit-Limit header. But when I go to http://twitter.com/statuses/public_timeline.xml, it's there. So I think you just need to use a different method.
It still says 150, though!

Categories

Resources