views:

211

answers:

1

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;
        }
+3  A: 

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.

Jon Skeet
A very clear, concise answer; but then no surprise there! +1
Mitch Wheat
You are correct! Thank you very much!
Ben