避免 WebRequestObject 中出现异常

发布于 2024-09-10 12:42:13 字数 632 浏览 8 评论 0原文

我正在从网站读取数据,如下所示:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一抹淡然 2024-09-17 12:42:13

与建立网络连接所需的时间相比,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文