web request timeout handling?

北城以北 提交于 2019-12-06 03:47:27

问题


HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 20000;
using (WebResponse response = request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
    var result = reader.ReadToEnd();
    // Do something with result
}

In the above example I have a timeout defined, if it happens to hit the timeout how would I know, the result would be empty ?

Do I receive any reponse types ?

How can I make sure I got timed out ?


回答1:


GetResponse() would throw a WebException. It's simple to test exactly what happens though - set the timeout to 1ms and try to hit anything which takes a while to come back.

In fact, the documentation states this explicitly:

If the timeout period expires before the resource can be returned, a WebException is thrown.




回答2:


Your HttpWebRequest.GetResponse call will throw a WebException when;

Abort was previously called.    
-or-    
The time-out period for the request expired.
-or-    
An error occurred while processing the request.

Catch this exception.

I used to just pull my network cable out to test this sort of thing although you could be more elegant and use a proxy tool and block that particular request.




回答3:


You should probably be using HTTPWebResponse. It has a status code that tells you that information and more. HTTPWebResponse is a descendant of WebResponse.



来源:https://stackoverflow.com/questions/5232077/web-request-timeout-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!