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
Signature | Description |
---|---|
protected HttpWebRequest() | Initializes a new instance of the HttpWebRequest class. (protected – for inheritance only) |
Properties
Property | Type | Description |
---|---|---|
Method | string | HTTP method (GET, POST, etc.). Default is GET . |
Headers | WebHeaderCollection | Request headers collection. |
ContentLength | long | Length of request data. |
ContentType | string | MIME type of request data. |
Credentials | ICredentials | Authentication credentials. |
Timeout | int | Time-out value in milliseconds. |
AllowAutoRedirect | bool | Whether the request follows redirects automatically. |
UserAgent | string | User-Agent header string. |
Methods
Method | Return Type | Description |
---|---|---|
GetResponse() | WebResponse | Gets the response from the Internet resource. |
GetResponseAsync() | Task<WebResponse> | Asynchronously gets the response. |
GetRequestStream() | Stream | Gets the request stream for writing data. |
GetRequestStreamAsync() | Task<Stream> | Asynchronously gets the request stream. |
Abort() | void | Aborts 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.