为什么HttpWebRequest会在第3次或更多次呼叫时超时?

时间:2014-03-19 10:14:02

标签: c# timeout httpwebrequest httpwebresponse

我需要检查网址是否存在,然后是我的代码:

   private bool CheckConnection(String URL)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.UseDefaultCredentials = true;
            request.KeepAlive = false;
            request.Timeout = 5000;
            request.ReadWriteTimeout = 5000;
            request.ServicePoint.ConnectionLeaseTimeout = 5000;
            request.ServicePoint.MaxIdleTime = 5000;
            bool bReturn = false;
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                bReturn = (response.StatusCode == HttpStatusCode.OK);
            }
            request.Abort();

        return bReturn;
        }
        catch
        {
            return false;
        }
    }

我收到消息"超时"在第3次通话时,我搜索并修复但无法成功。 任何人都可以帮助我吗?

全部谢谢

2 个答案:

答案 0 :(得分:2)

我正在努力解决同样的问题,经过一些R& D我在循环中声明响应代码后关闭HttpResponse对象进行了故障排除:response.Close();

我的代码:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
int respcode = (int)response.StatusCode;
Assert.IsTrue(respcode == 302 || respcode == 200);
response.Close();

答案 1 :(得分:0)

尝试下面的代码。一旦我有同样的问题,我使用这个例子修复它。希望这也适合你。

  using (var client = new WebClient())
        {
          var values = new NameValueCollection
         {
            { "key", "This is a test that posts this string to a Web server." }
         };
            string url = "http://www.contoso.com/PostAccepter.aspx";
            byte[] result = client.UploadValues(url, values);
            Console.WriteLine(Encoding.UTF8.GetString(result));
        }