Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# HTTP web request keeps timing out

I am making a Http Webrequest to an available site that I can visit fine, but the HTTP Web request keeps timing out. Is there any reason why this code might allow it to timeout when it shouldn't?

I've tried upping the timeout setting, but it still continues to timeout.

    Uri CameraUrl = new Uri("http://" + cfg_cameraIps[i]);
    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(CameraUrl);
    myRequest.Timeout = 5000;

    myRequest.Method = "HEAD";

    try
    {
        HttpWebResponse webresponse;
        webresponse = (HttpWebResponse)myRequest.GetResponse();

        if (webresponse.StatusCode.ToString() == "OK")
        {
            continue;
        }
like image 900
Ben Avatar asked Jan 03 '10 09:01

Ben


1 Answers

You're not closing your web response - if you find that the first couple of requests work, but ones after that don't, then that's the problem. It's trying to reuse the existing connection to the server, but it can't because you haven't closed the response.

Change your code to:

using (HttpWebResponse webresponse = (HttpWebResponse) myRequest.GetResponse())
{
    if (webresponse.StatusCode == HttpStatusCode.OK)
    {
        continue;
    }
    ...
}

and see if that helps.

If it's failing on the very first request to the server, then that's something different. In that case, use Wireshark to see what's going on at the network level.

Note that in the code above I've also removed the string conversion in favour of comparing the status codes directly.

like image 197
Jon Skeet Avatar answered Oct 04 '22 03:10

Jon Skeet