In the .NET framework, using the HttpWebRequest and HttpWebResponse classes to initiate and receive HTTP requests is a common practice. With these classes, we can send HTTP requests to the server and receive responses. Retrieving the HTTP status code is a critical step when processing HTTP responses because it indicates whether the request was successful or what type of error occurred.
Here is an example demonstrating how to use HttpWebRequest and HttpWebResponse to retrieve the HTTP status code:
csharpusing System; using System.Net; class Program { static void Main() { try { // Create HttpWebRequest object HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com"); // Send request and receive response using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { // Retrieve HTTP status code HttpStatusCode statusCode = response.StatusCode; Console.WriteLine("HTTP Status Code: " + (int)statusCode + " " + statusCode); } } catch (WebException ex) { // Handle exception, which may include network errors or response errors if (ex.Response is HttpWebResponse errorResponse) { // Retrieve HTTP status code of error response HttpStatusCode errorCode = errorResponse.StatusCode; Console.WriteLine("Error HTTP Status Code: " + (int)errorCode + " " + errorCode); } } } }
In this example, we first create an HttpWebRequest object and set the URL for the request. Then, we call the GetResponse method to send the request and receive the server's response. Using the using keyword automatically handles the disposal of response resources.
The GetResponse method returns an HttpWebResponse object, from which we can access the HTTP status code using its StatusCode property. This property is an enumeration value of HttpStatusCode, which includes all HTTP status codes, such as HttpStatusCode.OK representing 200 and HttpStatusCode.NotFound representing 404.
If an exception occurs during the request (e.g., network errors or server errors), it is caught in the catch block. Here, we check if the exception contains a response (WebException.Response), and if so, we can retrieve the error HTTP status code from this response.
By doing this, we can handle the HTTP status code in the application appropriately, such as retrying the request or displaying error messages.