.NET

.NET API Documentation

HttpWebRequest Class

Provides an HTTP-specific implementation of the WebRequest class. Use this class to make HTTP requests to resources identified by a URI.

Namespace

System.Net

Assembly

System.Net.Requests.dll

Syntax

public sealed class HttpWebRequest : WebRequest, ISerializable

Constructors

SignatureDescription
protected HttpWebRequest()Initializes a new instance of the HttpWebRequest class. (protected – for inheritance only)

Properties

PropertyTypeDescription
MethodstringHTTP method (GET, POST, etc.). Default is GET.
HeadersWebHeaderCollectionRequest headers collection.
ContentLengthlongLength of request data.
ContentTypestringMIME type of request data.
CredentialsICredentialsAuthentication credentials.
TimeoutintTime-out value in milliseconds.
AllowAutoRedirectboolWhether the request follows redirects automatically.
UserAgentstringUser-Agent header string.

Methods

MethodReturn TypeDescription
GetResponse()WebResponseGets the response from the Internet resource.
GetResponseAsync()Task<WebResponse>Asynchronously gets the response.
GetRequestStream()StreamGets the request stream for writing data.
GetRequestStreamAsync()Task<Stream>Asynchronously gets the request stream.
Abort()voidAborts the request.

Example

// Synchronous GET request
var request = (HttpWebRequest)WebRequest.Create("https://api.example.com/data");
request.Method = "GET";
request.Accept = "application/json";

using var response = (HttpWebResponse)request.GetResponse();
using var reader = new StreamReader(response.GetResponseStream());
string json = reader.ReadToEnd();
Console.WriteLine(json);

Remarks

HttpWebRequest is considered legacy for new development. Microsoft recommends using HttpClient for most scenarios due to its async nature and better resource management.

See Also