必须设置 ThrowOnAnyError = true; 不然设置TimeOut也不会报异常,
client.Timeout = iTimeOut * 1000;
client.ThrowOnAnyError = true; //设置不然不会报异常
而且很多时候并不是显示TimeoutException, 而是显示 WebException , 所以一般如下设置try/catch就可以保证大部分情况下能正常工作, 而不是一直挂在那里不返回也不报错.
try
{
IRestResponse response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
if (response.Content.Length > iMinHtmlLen && response.Content.Contains(CheckStr))
{
long elMs = sw.ElapsedMilliseconds;
item.CheckLastDelayMs = elMs;
}
else
{ item.CheckLastErrMsg = ($"返回长度小于{iMinHtmlLen}或搜索不到 {CheckStr} "); }
}
else
{
string retContent = (response.Content.Length < 200) ? response.Content : response.Content.Substring(0,200) ;
item.CheckLastErrMsg = ($"返回码!=OK {response.StatusCode} 前200字节: {retContent}");
}
}
catch (TimeoutException)
{ item.CheckLastErrMsg = ($"TimeoutException"); }
catch (System.Net.Http.HttpRequestException)
{ item.CheckLastErrMsg = ($"HttpRequestException"); }
catch (WebException)
{ item.CheckLastErrMsg = ($"WebException"); }