我正在尝试获取网页的标题。下面的代码块完成了这项工作 但是,当页面被拒绝时,我根本无法获得任何标题。有办法吗?
由于
public Int32 CheckURLStatus(string uri, out HttpWebResponse _response)
{
//Get response header
_response = null;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
HttpWebRequest _request = (HttpWebRequest)WebRequest.Create(uri);
_request.Method = "GET";
_request.AllowAutoRedirect = true;
_request.Accept = "*/*";
_request.MaximumAutomaticRedirections = 4;
_request.UseDefaultCredentials = true;
_request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
Int32 statusCode = 404;
try
{
_response = (HttpWebResponse)_request.GetResponse();
statusCode = Convert.ToInt32(_response.StatusCode);
}
catch (Exception ex)
{
_response = null;
}
return statusCode;
}
答案 0 :(得分:0)
如果任何StatusCode不是200,则GetResponse()方法抛出WebException。要获取状态代码,您必须处理此异常并从异常中的响应中获取StatusCode。
我已经更改了代码以获取响应代码,即使在WebException的情况下:
public Int32 CheckURLStatus(string uri, out HttpWebResponse _response)
{
//Get response header
_response = null;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
HttpWebRequest _request = (HttpWebRequest)WebRequest.Create(uri);
_request.Method = "GET";
_request.AllowAutoRedirect = true;
_request.Accept = "*/*";
_request.MaximumAutomaticRedirections = 4;
_request.UseDefaultCredentials = true;
_request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
Int32 statusCode = 404;
try
{
_response = (HttpWebResponse)_request.GetResponse();
statusCode = Convert.ToInt32(_response.StatusCode);
}
catch (WebException ex)
{
statusCode = Convert.ToInt32(((HttpWebResponse)ex.Response).StatusCode);
_response = null;
}
return statusCode;
}
您也可以查看ex.Response.Headers,您将获得响应的HTTP标头。