Reputation: 5047
EDIT: Solved, the problem was server-side.
I'm using C# and .NET2 and I wonder is that a WebRequest bug.. I do several good requests with this method and all is fine, but after that every time I get "The operation has timed out.". I really don't understand why is that.
public string RequestPage(string url) {
HttpWebRequest req = null;
string line = "";
string site = "";
try {
req = (HttpWebRequest) WebRequest.Create(url.Trim());
req.Timeout = 10000;
StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream());
while ((line = reader.ReadLine()) != null) {
site += line;
}
return site;
} catch (Exception ex) {
MessageBox.Show("ERROR " + ex.Message);
}
return null;
}
Upvotes: 2
Views: 835
Reputation: 217401
I don't know if this solves your problem, but you should always dispose a HttpWebResponse (and other objects that implement IDisposable) when you're done:
public string RequestPage(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = 10000;
using (WebResponse resp = req.GetResponse())
using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
If you don't actually require all the features of HttpWebRequest, you can use WebClient instead:
public string RequestPage(string url)
{
using (WebClient client = new WebClient())
{
return client.DownloadString(url);
}
}
Upvotes: 2
Reputation: 1503290
You're not disposing of the response:
using (WebResponse response = req.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream())
{
while ((line = reader.ReadLine()) != null) {
site += line;
}
}
Basically there are pooled connections per server that you talk to. You're running out of them because you're not closing the response. The above should sort it out.
Additionally:
StringBuilder
to concatenate text content in a loop.reader.ReadToEnd()
instead.Upvotes: 2