我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 的列表。