我正在编写一些必须执行基本 HTTP GET 和 POST 的 C# 2.0 代码。我正在使用 System.Net.HttpWebRequest 发送这两种类型的请求,并使用 System.Net.HttpWebResponse 来接收这两种请求。我的 GET 代码如下所示:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format("{0}?{1}",
URLToHit,
queryString));
request.Method = "GET";
request.Timeout = 1000; // set 1 sec. timeout
request.ProtocolVersion = HttpVersion.Version11; // use HTTP 1.1
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
catch(WebException e)
{
// If I do anything except swallow the exception here,
// I end up in some sort of endless loop in which the same WebException
// keeps being re-thrown by the GetResponse method. The exception is always
// right (ie: in cases when I'm not connected to a network, it gives a
// timed out error, etc...), but it should not be re-thrown!
}
和我的 POST 代码非常相似。
当 URLToHit 返回 HTTP 状态 200 时,最后一行工作正常,但在任何其他情况下(即:非 200 HTTP 状态、无网络连接等),都会引发 System.Net.WebException(这是预期的,根据到 MSDN 文档)。但是,我的代码从未超过那条线。
当我尝试对此进行调试时,我发现我无法跳过或继续越过最后一行。当我尝试这样做时,会重新发出请求并重新抛出异常。
关于我可以做些什么来使请求只发出一次的任何想法?我从来没有在任何基于异常的代码中看到过这样的事情,而且我没有想法。我的代码的任何其他部分都不会发生类似的情况,只是处理 System.Net 功能和构造的部分。
谢谢!
(更新:围绕 GetRequest 方法添加了 try/catch)