Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse
Console.Write((int)response.StatusCode);
HttpStatusCode (the type of response.StatusCode
) is an enumeration where the values of the members match the HTTP status codes, e.g.
public enum HttpStatusCode
{
...
Moved = 301,
OK = 200,
Redirect = 302,
...
}
You have to be careful, server responses in the range of 4xx and 5xx throw a WebException. You need to catch it, and then get status code from a WebException object:
try
{
wResp = (HttpWebResponse)wReq.GetResponse();
wRespStatusCode = wResp.StatusCode;
}
catch (WebException we)
{
wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}
As per 'dtb' you need to use HttpStatusCode, but following 'zeldi' you need to be extra careful with code responses >= 400.
This has worked for me:
HttpWebResponse response = null;
HttpStatusCode statusCode;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
response = (HttpWebResponse)we.Response;
}
statusCode = response.StatusCode;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
sResponse = reader.ReadToEnd();
Console.WriteLine(sResponse);
Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());