Class System.Net.WebRequest

Namespace: System.Net

Assembly: System (in System.dll)

Summary

Represents a request to a Uniform Resource Identifier (URI) resource.

The WebRequest class is an abstract base class that enables you to send requests to a URI and receive responses from the URI. Specific implementations of WebRequest, such as HttpWebRequest and FtpWebRequest, handle the details of sending requests for specific protocols.

Remarks

WebRequest provides a common interface for network access. You can use WebRequest.Create(string requestUri) to create a request object that is appropriate for the specified URI. The system then determines the correct protocol handler and returns an instance of the appropriate derived class.

When working with HTTP or HTTPS URIs, you should cast the returned WebRequest object to an HttpWebRequest object to access HTTP-specific members.

It is important to close the response stream obtained from a WebRequest to release resources.

Methods

Create(string requestUri)

Creates a new WebRequest instance for the specified resource.

public static WebRequest Create(string requestUri)

Create(Uri requestUri)

Creates a new WebRequest instance for the specified resource.

public static WebRequest Create(Uri requestUri)

Abort()

Aborts any pending asynchronous request.

public virtual void Abort()

GetResponse()

Sends the request to the server and waits for a response.

public virtual WebResponse GetResponse()

Properties

RequestUri

Gets the URI of the resource that is requested.

public Uri RequestUri { get; }

Method

Gets or sets the HTTP method to use for the request.

public string Method { get; set; }

ContentLength

Gets or sets the content length of the data being sent to the server.

public long ContentLength { get; set; }

ContentType

Gets or sets the content type of the data being sent to the server.

public string ContentType { get; set; }

Example

// C# Example
using System;
using System.Net;
using System.IO;

public class WebRequestExample
{
    public static void Main(string[] args)
    {
        try
        {
            // Create a request for the specified URL.
            WebRequest request = WebRequest.Create("https://www.example.com");

            // If required by the server, set the ContentLength property of the WebRequest.
            request.ContentLength = 4;

            // Set the Method property of the request to POST.
            request.Method = "POST";

            // You can optionally add headers here.
            // request.Headers.Add("Authorization", "Bearer YOUR_TOKEN");

            // Get the request stream.
            using (Stream dataStream = request.GetRequestStream())
            {
                // Write the data to be sent to the server.
                using (StreamWriter writer = new StreamWriter(dataStream))
                {
                    writer.Write("test");
                }
            }

            // Get the response.
            using (WebResponse response = request.GetResponse())
            {
                Console.WriteLine(((HttpWebResponse)response).StatusDescription);

                // Get the stream containing the response.
                using (Stream dataStream = response.GetResponseStream())
                {
                    // Read the stream.
                    using (StreamReader reader = new StreamReader(dataStream))
                    {
                        string responseFromServer = reader.ReadToEnd();
                        Console.WriteLine(responseFromServer);
                    }
                }
            }
        }
        catch (WebException ex)
        {
            Console.WriteLine("An error occurred: {0}", ex.Message);
        }
    }
}

Create(string requestUri)

Initializes a new instance of the WebRequest class with the specified URI.

This static method creates a new WebRequest object for the specified resource. The system determines the correct protocol handler and returns an instance of the appropriate derived class (e.g., HttpWebRequest for HTTP/HTTPS URIs).

Parameters

Name Type Description
requestUri string The Uniform Resource Identifier (URI) of the resource that is requested.

Return Value

A WebRequest object for the specified resource.

Create(Uri requestUri)

Initializes a new instance of the WebRequest class with the specified Uri object.

Similar to the string overload, this method provides flexibility by accepting a Uri object directly.

Parameters

Name Type Description
requestUri Uri A Uri object representing the resource that is requested.

Return Value

A WebRequest object for the specified resource.

Abort()

Aborts any pending asynchronous request.

Use this method to cancel an asynchronous network operation that is in progress.

Parameters

None

Return Value

None

GetResponse()

Sends the request to the server and waits for a response.

This method sends the request and blocks until a response is received. For asynchronous operations, use BeginGetResponse and EndGetResponse.

Parameters

None

Return Value

A WebResponse object containing the response from the server.

RequestUri

Gets the Uniform Resource Identifier (URI) of the resource that is requested.

This property returns the URI that was passed to the Create method or set in the constructor.

Property Value

A Uri object representing the requested resource.

Method

Gets or sets the HTTP method to use for the request (e.g., GET, POST, PUT).

The default value is "GET". For HttpWebRequest, common values include "GET", "POST", "PUT", "DELETE", and "HEAD".

Property Value

string: The HTTP method to use for the request.

ContentLength

Gets or sets the content length of the data being sent to the server.

This property is important for requests that send data, such as POST requests. It indicates the size of the request body in bytes.

Property Value

long: The number of bytes to be sent to the server.

ContentType

Gets or sets the content type of the data being sent to the server.

This property is typically used for POST and PUT requests and specifies the MIME type of the data in the request body (e.g., "application/json", "application/x-www-form-urlencoded").

Property Value

string: The content type of the data being sent.