0
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 行崩溃时应该得到响应,有什么办法解决这个问题?

4

1 回答 1

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());
        }
    }
于 2013-07-27T19:08:01.330 回答