Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 找不到页面时发生GetResponse错误_C#_Http - Fatal编程技术网

C# 找不到页面时发生GetResponse错误

C# 找不到页面时发生GetResponse错误,c#,http,C#,Http,当地址无效时,软件在应该得到响应的代码第三行崩溃,有没有办法解决这个问题?你可以得到这样的响应 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/afakepage"); request.Method = WebRequestMethods.Http.Head; HttpWebResponse response = (HttpWebResponse)request.GetRespon

当地址无效时,软件在应该得到响应的代码第三行崩溃,有没有办法解决这个问题?

你可以得到这样的响应

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;

这修复了崩溃错误,谢谢!
    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());
        }
    }