开发者

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 cod开发者_如何转开发e 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;
        }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜