避免 WebRequestObject 中出现异常
我正在从网站读取数据,如下所示:
webRequestObj = (HttpWebRequest)WebRequest.Create("http://localhost/503errorPage.php");
theResponse = webRequestObj.GetResponse();
theResponseStream = theResponse.GetResponseStream();
theStreamReader = new StreamReader(theResponseStream);
theWholePage = theStreamReader.ReadToEnd();
如果我访问的页面有 503 错误,则该行:
theResponse = webRequestObj.GetResponse();
抛出 WebException:
The remote server returned an error: (503) Server Unavailable.
有没有办法检查网站是否返回 503 错误,而不是将所有内容都包装在 try/ 中catch 块并等待异常?我每秒进行多次更新,并且希望尽可能避免尝试/捕获。
I am reading data from a website as follows:
webRequestObj = (HttpWebRequest)WebRequest.Create("http://localhost/503errorPage.php");
theResponse = webRequestObj.GetResponse();
theResponseStream = theResponse.GetResponseStream();
theStreamReader = new StreamReader(theResponseStream);
theWholePage = theStreamReader.ReadToEnd();
If I get to a page that has a 503 error, the line:
theResponse = webRequestObj.GetResponse();
throws a WebException:
The remote server returned an error: (503) Server Unavailable.
Is there a way check if the website returns a 503 error instead of wrapping everything up in a try/catch block and waiting for the exception? I am doing many updates per second and would like to avoid the try/catch if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
与建立网络连接所需的时间相比,try/catch 的成本微乎其微。真的,如果性能是您所担心的 - 别担心了:)
现在我很乐意承认,在更哲学的层面上,您无法进行推测性调用 - 一种
TryGetResponse
- 但我不知道有什么方法可以做到这一点。其中一种异步方法可能会起作用,但这最终可能会改变相当多的代码。顺便说一句,请确保您处理响应和流 - 如果您不处理响应,您将受到与同一服务器建立的连接数量的限制。
The cost of the try/catch will be miniscule compared to the time it takes to make the network connection. Really, if performance is what you're worried about - quit worrying :)
Now I'll readily admit that it's annoying at a more philosophical level that you can't make a speculative call - a sort of
TryGetResponse
- but I don't know of a way of doing that. It's possible that one of the async approaches would work, but that ends up potentially changing quite a lot of code.Btw, make sure you dispose of the response and the stream - if you don't dispose of the response, you'll be limited in terms of how many connections you can make to the same server.