blez
blez

Reputation: 5047

WebRequest bug?

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

Answers (2)

dtb
dtb

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

Jon Skeet
Jon Skeet

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:

  • That's a potentially very slow way of building up a string. Use a StringBuilder to concatenate text content in a loop.
  • Do you really want to remove all the line breaks? If not, just use reader.ReadToEnd() instead.

Upvotes: 2

Related Questions