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行崩溃,以解决这个问题吗?
答案 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());
}
}