乏mily

导航

如何处理C#的HttpWebResponse的GetResponse中的超时异常

程序中,有时会遇到超时的异常,需要进行处理,用一般的try...catch(Exception ex)...会发现ex没有status属性,此时使用WebException捕获异常:

try
{
  resp = (HttpWebResponse)req.GetResponse();
    // ...
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError)
    {
        var response = ex.Response as HttpWebResponse;
        if (response != null)
        {
            Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
        }
        else
        {
            // no http status code available
        }
    }
    else
    {
        // no http status code available
    }
}

 

posted on 2016-03-21 16:19  乏mily  阅读(2426)  评论(0编辑  收藏  举报