我正在创建一个函数来测试给定的网址并获取状态代码,问题是 HttpWebRequest 变量将返回 NULL - 如代码中注释的那样 - 如果状态为 tineOut 或无法访问 url,而它应该返回 408 进行超时。
try
{
request = (HttpWebRequest)WebRequest.Create(url); //set http request
request.Timeout = timeOut * 1000;
request.ContinueTimeout = timeOut * 1000;
stopwatch.Start(); //start timer
response = (HttpWebResponse)request.GetResponse(); //this will return NULL if URL is timedOut or not reachable
response.Close(); //close session
stopwatch.Stop(); //Stop timer
statusCode = (int)response.StatusCode; //save status code as int
info[0] = stopwatch.Elapsed.TotalMilliseconds.ToString(); //store Latency to info
info[1] = statusCode.ToString(); //store status code
info[2] = response.StatusDescription; //store status description
}
catch (WebException err) //catch timeOut case
{
stopwatch.Stop();
var responseObj = err.Response as HttpWebResponse; //err.Response is NULL as well.
info[0] = stopwatch.Elapsed.TotalMilliseconds.ToString(); //store Latency to info
info[1] = (int)responseObj.StatusCode + "";//store status code
info[2] = responseObj.StatusDescription; //store status description
}
最后,我无法将这两个解决方案应用于我当前的代码,因为它们似乎与我的问题相同。
如何为 HttpWebRequest 定义更激进的超时?
捕获 HttpWebRequest 超时
如果需要任何澄清,请通知我。
请求。GetResponse(( 返回来自您尝试与之通信的 Web 服务器的响应。
现在,当您遇到超时或错误的 URL 时,来自 Web 服务器的响应将为 NULL,因为您没有从该服务器获得任何信息。
您可以使用从 WebException 获得的状态来检测超时。
这是您的 http 通信的通用捕获块。请注意,您的 408 实际上是不正确的,任何其他与 http 无关的问题最终都将以 -1 结束。
catch (WebException wbEx)
{
if (wbEx.Status == WebExceptionStatus.ProtocolError)
{
if (wbEx.Response is HttpWebResponse response)
{
returnStatusCode = (int) response.StatusCode;
}
else // should not happen
{
returnStatusCode = -1;
}
}
else
{
if (wbEx.Status == WebExceptionStatus.Timeout)
{
returnStatusCode = 408; // now this is not right because this is CLIENT timeout.
}
}
}
catch
{
returnStatusCode = -1;
}