GetResponse找不到页面时出错

时间:2013-07-27 18:58:18

标签: c# http

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/afakepage");
request.Method = WebRequestMethods.Http.Head;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
bool pageExists = response.StatusCode == HttpStatusCode.OK;

当地址无效时,如果软件应该得到响应,软件会在代码的第3行崩溃,以解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

你可以得到这样的回复

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/afakepage");
    request.Method = WebRequestMethods.Http.Head;
    try
    {
        using (WebResponse response = request.GetResponse())
        {

        }
    }
    catch (WebException e)
    {
        using (WebResponse response = e.Response)
        {
            HttpWebResponse httpResponse = (HttpWebResponse) response;
            MessageBox.Show(httpRespnse.StatusCode.ToString());
        }
    }