I am trying to obtain the headers of a webpage. The code block below does the job.
However, when a page is 401 denied, I can’t get any headers at all. Is there a way?
Thanks
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;
}
In case of any StatusCode that is not 200 the GetResponse() method throws a WebException. To get the status code you have to handle this Exception and get the StatusCode from the Response that is in the Exception.
I´ve changed your code to get the response code even in the case of WebException:
Also you can check the ex.Response.Headers and you will have the HTTP headers of the response.