【发布时间】:2013-09-06 20:03:29
【问题描述】:
我在我的应用程序中使用HttpWebRequest,它正在检查多个线程中的一些URI。我收到多种类型的超时异常。
- 操作已超时
- 远程服务器返回错误:(504) 网关超时。
他们的详细信息如下:
System.Net.WebException:操作已超时 System.Net.HttpWebRequest.GetResponse() 在......
和
System.Net.WebException:远程服务器返回错误:(504) 网关超时。在 System.Net.HttpWebRequest.GetResponse() 在 ....
这两者有什么不同。
我的功能是这样的:
public bool CheckUri(Uri m_url)
{
try
{
HttpWebRequest request = HttpWebRequest.Create(m_url) as HttpWebRequest;
request.UserAgent = "MyUserAgent";
//For: The underlying connection was closed: An unexpected error occurred on a receive.
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "HEAD"; //Get only the header information
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
int statusCode = (int)response.StatusCode;
if (statusCode >= 100 && statusCode < 400) //Good requests
{
string sContent = null;
using (var stream = response.GetResponseStream())
using (StreamReader loResponseStream = new StreamReader(stream))
sContent = loResponseStream.ReadToEnd();
return true;
}
else
{
return false;
//hard to reach here
}
}
}
//vexing exception
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError) //400 errors
{
var response = ex.Response as HttpWebResponse;
if (response != null)
{
Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
Console.WriteLine(response.StatusCode);
}
}
else
{
Console.WriteLine(ex.Message);
}
return false;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
另外,如果有人能告诉我,如果多个线程使用不同的 URI 调用此方法,是否会出现问题。我没有得到任何跨线程异常。此方法实际上是 Windows 服务的一部分,该服务监视近 200 个 URI 的列表。
【问题讨论】:
-
一个是直接超时,即你的具体操作;另一种表示网关(通往目的地的路线)超时。你谷歌了吗?有很多参考资料。
-
@GrantThomas,我试过了,但我不确定它们是相同还是不同。
标签: c# .net system.net.webexception