首页 文章

超时异常不会按时发生

提问于
浏览
1

我使用httpwebrequest(Timeout = 2000)和webproxy编写了以下代码
由于错误的url( "ww.google.com" ),以下代码始终会抛出异常

当我运行程序时,我交替得到两种异常
1.远程服务器返回错误:(404)未找到(Web异常)
=>捕获此异常需要不到2000毫秒
=>此异常处理是正常的 .
.
2. A connection attempt failed because the connected party did not properly respond after a period of time or connected host has failed to respond (Socket Exception)
=> It takes 25 seconds or more to catch this exception
=> I set a request 2000ms timeout but it does not work !!!!

I want to catch exceptions if there is no response within 2 seconds
我该怎么办?

try 
{ 
       request = (HttpWebRequest)WebRequest.Create("https://ww.google.com"); 
       request.Proxy = proxy; 
       request.Method = "GET"; 
       request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"; 
       request.Timeout = 2000; 
       response = (HttpWebResponse)request.GetResponse(); 
       if ((response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.Redirect)) 
       { 
              StreamReader sreader = new StreamReader(response.GetResponseStream(), Encoding.Default); 
              gethtml = sreader.ReadToEnd(); 
              sreader.Close(); 
       } 
} 
catch (Exception ex) 
{ 
       throw ex; 
}

1 回答

  • 0

    具有讽刺意味的是,在使用无效的网址 https://ww.google.com 进行测试时,您无意中绊倒了一个地雷 . 有关详细信息,请参阅this post . 该帖子中提到的MSDN文档是here . 请注意 WebRequest.Create 返回 HttpWebRequest .

    基本上,它需要一段时间,因为URL未映射到IP地址,因此不会缓存在链中,每次向它发出请求时都需要完整的DNS查找 . 除非你在客户端使用自己的DNS缓存层,否则你真的无能为力,但坦白说它比它的 Value 更麻烦 .

相关问题