Reputation: 31383
I am trying to get the HTTP status code number from the HttpWebResponse
object returned from a HttpWebRequest
. I was hoping to get the actual numbers (200, 301,302, 404, etc.) rather than the text description. ("Ok", "MovedPermanently", etc.) Is the number buried in a property somewhere in the response object? Any ideas other than creating a big switch function? Thanks.
HttpWebRequest webRequest = (HttpWebRequest)WebRequest
.Create("http://www.gooogle.com/");
webRequest.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
//Returns "MovedPermanently", not 301 which is what I want.
Console.Write(response.StatusCode.ToString());
Upvotes: 345
Views: 435816
Reputation: 160
Here's how i am handling such a situation.
//string details = ...
//...
catch (WebException ex)
{
HttpStatusCode statusCode = ((HttpWebResponse)ex.Response).StatusCode;
if (statusCode == HttpStatusCode.Unauthorized)
{
Reconnect();
//...
}
else if (statusCode == HttpStatusCode.NotFound)
{
FileLogger.AppendToLog("[ERROR] Not Found: " + details);
}
else
{
FileLogger.AppendToLog("[ERROR] " + ex.Message + ": " + details);
}
}
Upvotes: 0
Reputation: 14401
Just coerce the StatusCode
to int
.
var statusNumber;
try {
response = (HttpWebResponse)request.GetResponse();
// This will have statii from 200 to 30x
statusNumber = (int)response.StatusCode;
}
catch (WebException we) {
// Statii 400 to 50x will be here
statusNumber = (int)we.Response.StatusCode;
}
Upvotes: 20
Reputation: 77
//Response being your httpwebresponse
Dim str_StatusCode as String = CInt(Response.StatusCode)
Console.Writeline(str_StatusCode)
Upvotes: 3
Reputation: 1673
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());
Upvotes: 26
Reputation: 4903
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;
}
Upvotes: 259
Reputation: 217411
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,
...
}
Upvotes: 468