HTTP
Status Codes
HttpWebRequest
HttpWebResponse
Programming

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

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Understanding HTTP Status Codes with HttpWebRequest and HttpWebResponse

When developing web applications, handling HTTP requests and responses is a fundamental task. HttpWebRequest and HttpWebResponse are .NET classes used for interacting with HTTP servers. This article dives deep into obtaining HTTP status codes from these classes, which are essential for determining the outcome of HTTP requests. We will also explore examples and precautions for effective and efficient HTTP communication.

Introduction to HTTP Status Codes

HTTP status codes are three-digit responses provided by a server indicating the outcome of an HTTP request. They are categorized into five groups:

  • 1xx (Informational): Request received, continuing process.
  • 2xx (Successful): The action was successfully received, understood, and accepted. For instance, 200 means OK.
  • 3xx (Redirection): Further action must be taken to complete the request, e.g., 301 for Moved Permanently.
  • 4xx (Client Error): The request contains bad syntax or cannot be fulfilled, like 404 for Not Found.
  • 5xx (Server Error): The server failed to fulfill a valid request. For example, 500 for Internal Server Error.

Retrieving HTTP Status Codes with HttpWebRequest and HttpWebResponse

In .NET, HttpWebRequest is used to send HTTP requests, and HttpWebResponse is used to receive the response from the server. Below is a method to illustrate how to obtain the HTTP status code from an HTTP request:

csharp
1using System;
2using System.Net;
3
4public class StatusCodeExample
5{
6    public static void GetHttpStatusCode(string url)
7    {
8        try
9        {
10            // Create a HttpWebRequest object using the specified URL
11            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
12            
13            // Get the response from the server
14            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
15            {
16                // Retrieve the status code
17                HttpStatusCode statusCode = response.StatusCode;
18                
19                // Display the HTTP status code
20                Console.WriteLine($"HTTP Status Code: {(int)statusCode} - {statusCode}");
21            }
22        }
23        catch (WebException ex)
24        {
25            // Handle the WebException and extract the status code from the response
26            if (ex.Response is HttpWebResponse httpResponse)
27            {
28                Console.WriteLine($"HTTP Status Code: {(int)httpResponse.StatusCode} - {httpResponse.StatusCode}");
29            }
30            else
31            {
32                Console.WriteLine($"Error: {ex.Message}");
33            }
34        }
35    }
36}

Explanation of Example Code

  1. HttpWebRequest Object: This object is created using the WebRequest.Create(url) method where url is the requested resource's URI.
  2. HttpWebResponse Object: The GetResponse() method sends the request and returns HttpWebResponse, which represents the response from the server.
  3. HttpStatusCode Property: This property of HttpWebResponse is used to get the status code of the response, cast into an integer for readability.
  4. Exception Handling: A WebException could be thrown due to network issues, DNS errors, or invalid responses. The status code can be extracted from WebException if the server responds with an error.

Common HTTP Status Codes and Their Meaning

Status CodeMeaningCategory
200OKSuccessful
301Moved PermanentlyRedirection
302FoundRedirection
304Not ModifiedRedirection ( cache )
400Bad RequestClient Error
401UnauthorizedClient Error
403ForbiddenClient Error
404Not FoundClient Error
500Internal Server ErrorServer Error
502Bad GatewayServer Error
503Service UnavailableServer Error

Enhancing HTTP Requests with Additional Functionality

  • Timeout Settings: Adjust timeout values to manage long-running requests using request.Timeout.
  • Custom Headers: Add headers with request.Headers.Add("Header-Name", "Header-Value") for additional request specifics.
  • Request Method: Change the request method (e.g., GET, POST) by setting request.Method.

Best Practices and Considerations

  1. Error Handling: Adequately handle exceptions and network errors to ensure robust applications.
  2. Security: Use HTTPS instead of HTTP to encrypt data.
  3. Resource Management: Always close HttpWebResponse objects using a using statement to free up system resources.
  4. Performance Monitoring: Monitor load time and status codes for potential optimization.

Conclusion

Handling HTTP status codes through HttpWebRequest and HttpWebResponse is critical in ensuring that your application's server communication runs smoothly. By understanding these codes, developers can implement appropriate responses and error-handling routines, ensuring high application resilience and a good user experience.


Course illustration
Course illustration

All Rights Reserved.