Aar*_*ron 5 c# system.net .net-2.0
我正在编写一些C#2.0代码,它必须执行基本的HTTP GET和POST.我正在使用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!
}
Run Code Online (Sandbox Code Playgroud)
我的POST代码非常相似.
当URLToHit返回HTTP状态200时,最后一行正常工作,但在任何其他情况下(即:非200 HTTP状态,没有网络连接等),抛出System.Net.WebException(这是预期的,根据到MSDN文档).但是,我的代码永远不会超越该行.
当我尝试调试它时,我发现我无法跳过或继续经过最后一行.当我尝试这样做时,重新发出请求并重新抛出异常.
关于我可以做什么来提出请求的任何想法只发出一次?我从来没有在任何基于异常的代码中看到过这样的事情,而且我没有想法.在我的代码的任何其他部分,只有处理System.Net功能和构造的部分,都不会发生这种情况.
谢谢!
(更新:在GetRequest方法周围添加了try/catch)
C# 中不存在“不间断”异常。要控制异常期间发生的情况,可以使用 try-catch 块。
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();
// Code here runs if GetResponse() was successful.
}
catch (WebException ex)
{
// Code here runs if GetResponse() failed.
}
// Code here is always run unless another exception is thrown.
Run Code Online (Sandbox Code Playgroud)
不存在“不间断异常”的原因是,如果出现异常,您的代码就不可能执行您的预期操作。例如,您希望“响应”变量包含什么?你会用它做什么?try-catch 块使您可以完全控制它。