Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

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()); 
like image 654
James Lawruk Avatar asked Aug 25 '09 20:08

James Lawruk


People also ask

How do I get my HTTP status code 200?

The HTTP 200 OK success status response code indicates that the request has succeeded. A 200 response is cacheable by default. The meaning of a success depends on the HTTP request method: GET : The resource has been fetched and is transmitted in the message body.

How can I get HTTP status code?

Just use Chrome browser. Hit F12 to get developer tools and look at the network tab. Shows you all status codes, whether page was from cache etc.

What is HttpWebResponse C#?

This class contains support for HTTP-specific uses of the properties and methods of the WebResponse class. The HttpWebResponse class is used to build HTTP stand-alone client applications that send HTTP requests and receive HTTP responses.

What is a 207 HTTP response?

The HTTP Status Code 207 means that the message body that follows is by default an XML message and can contain a number of separate response codes, depending on how many sub-requests were made.


2 Answers

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,     ... } 
like image 102
dtb Avatar answered Sep 22 '22 21:09

dtb


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; } 
like image 27
zeldi Avatar answered Sep 22 '22 21:09

zeldi