System.Net.HttpWebRequest Class
Provides an application programming interface to a Uniform Resource Identifier (URI) and supports opening Uniform Resource Locators (URLs) with Uniform Resource Identifiers (URIs). This class is the primary .NET Framework class used to send and receive data using Uniform Resource Locators (URLs) through HTTP.
Summary
The HttpWebRequest class is used to send HTTP requests to a web server and receive responses. It allows you to control various aspects of the request, such as the HTTP method, headers, content, and authentication.
Inheritance
System.ObjectSystem.MarshalByRefObjectSystem.IO.StreamSystem.Net.WebRequestSystem.Net.HttpWebRequest
Syntax
public sealed class HttpWebRequest : System.Net.WebRequest
Remarks
HttpWebRequest is used for HTTP communication. For other protocols, use the appropriate WebRequest derived class.
This class is not thread-safe. When you use a HttpWebRequest instance from multiple threads, you must synchronize the access to the instance.
Constructors
Properties
AllowAutoRedirect: Gets or sets a value that indicates whether to automatically follow HTTP redirects.AuthenticationLevel: Gets or sets the authentication level for this request.CachePolicy: Gets or sets the cache policy for this request.ClientCertificate: Gets or sets the client certificate used to authenticate the request.ContentLength: Gets or sets the number of bytes to send to the server.ContentType: Gets or sets the type of content sent to the server.Credentials: Gets or sets the ICredentials used for authentication.Expect: Gets or sets the value of the Expect HTTP header.Host: Gets or sets the value of the Host HTTP header.KeepAlive: Gets or sets a value indicating whether to keep the connection alive.Method: Gets or sets the HTTP method for the request.ProtocolVersion: Gets or sets the HTTP protocol version to use for the request.Proxy: Gets or sets the IWebProxy used to send requests.ReadWriteTimeout: Gets or sets the time (in milliseconds) to wait for a read or write operation to complete.RequestUri: Gets the Uri to which the request is sent.SendChunked: Gets or sets a value indicating whether to send data in chunks.ServicePoint: Gets the ServicePoint for the connection.Timeout: Gets or sets the time (in milliseconds) to wait for the server to send the response.TransferEncoding: Gets or sets the value of the Transfer-Encoding HTTP header.Url: Gets or sets the Uri to which the request is sent.UserAgent: Gets or sets the value of the User-Agent HTTP header.
Methods
Abort(): Aborts the current asynchronous request to a resource.GetRequestStream(): Returns a Stream object that you can use to send data to the server.GetRequestStreamAsync(): Returns a task that represents the asynchronous operation.GetResponse(): Sends the request to the server and waits for a response.GetResponseAsync(): Returns a task that represents the asynchronous operation.
Example
Sending a GET Request
This example demonstrates how to send a simple GET request and read the response.
using System;
using System.Net;
using System.IO;
using System.Text;
public class Example
{
public static void Main(string[] args)
{
try
{
// Create a request object.
HttpWebRequest request = (
HttpWebRequest)WebRequest.Create(
"http://www.contoso.com/page.html");
// If required by the server, set the Credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (
HttpWebResponse)request.GetResponse();
// Print the status description.
Console.WriteLine(
"Status: {0}", response.StatusDescription);
// Get the stream for reading the content.
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(
"Response: {0}", responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
catch (WebException e)
{
Console.WriteLine("An error occurred: {0}", e.Message);
}
}
}
Sending a POST Request
This example demonstrates sending data using a POST request.
using System;
using System.Net;
using System.IO;
using System.Text;
public class PostExample
{
public static void Main(string[] args)
{
try
{
string postData = "param1=value1¶m2=value2";
byte[] byteArray = new byte[postData.Length / 2];
byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest request = (
HttpWebRequest)WebRequest.Create("http://www.contoso.com/post.html");
// Configure the request.
request.Method = "POST";
request.ContentLength = byteArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
// Write data to the request stream.
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
// Get the response.
HttpWebResponse response = (
HttpWebResponse)request.GetResponse();
Console.WriteLine(
"Response: {0}", response.StatusDescription);
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
response.Close();
}
catch (WebException e)
{
Console.WriteLine("An error occurred: {0}", e.Message);
}
}
}
Constructor
HttpWebRequest(Uri requestUri)
Initializes a new instance of the HttpWebRequest class with the specified Uri.
public HttpWebRequest(Uri requestUri);
Properties
AllowAutoRedirect
Gets or sets a value that indicates whether to automatically follow HTTP redirects. Inherited from WebRequest
public bool AllowAutoRedirect { get; set; }
AuthenticationLevel
Gets or sets the authentication level for this request. Inherited from WebRequest
public System.Security.Authentication.AuthenticationLevel AuthenticationLevel { get; set; }
CachePolicy
Gets or sets the cache policy for this request. Inherited from WebRequest
public System.Net.Cache.RequestCachePolicy CachePolicy { get; set; }
ClientCertificate
Gets or sets the client certificate used to authenticate the request.
public System.Security.Cryptography.X509Certificates.X509Certificate ClientCertificate { get; set; }
ContentLength
Gets or sets the number of bytes to send to the server. Inherited from WebRequest
public long ContentLength { get; set; }
ContentType
Gets or sets the type of content sent to the server.
public string ContentType { get; set; }
Credentials
Gets or sets the ICredentials used for authentication. Inherited from WebRequest
public System.Net.ICredentials Credentials { get; set; }
Expect
Gets or sets the value of the Expect HTTP header.
public string Expect { get; set; }
Host
Gets or sets the value of the Host HTTP header.
public string Host { get; set; }
KeepAlive
Gets or sets a value indicating whether to keep the connection alive.
public bool KeepAlive { get; set; }
Method
Gets or sets the HTTP method for the request. Inherited from WebRequest
public string Method { get; set; }
ProtocolVersion
Gets or sets the HTTP protocol version to use for the request.
public System.Version ProtocolVersion { get; set; }
Proxy
Gets or sets the IWebProxy used to send requests. Inherited from WebRequest
public System.Net.IWebProxy Proxy { get; set; }
ReadWriteTimeout
Gets or sets the time (in milliseconds) to wait for a read or write operation to complete. Inherited from WebRequest
public int ReadWriteTimeout { get; set; }
RequestUri
Gets the Uri to which the request is sent. Inherited from WebRequest
public Uri RequestUri { get; }
SendChunked
Gets or sets a value indicating whether to send data in chunks.
public bool SendChunked { get; set; }
ServicePoint
Gets the ServicePoint for the connection. Inherited from WebRequest
public System.Net.ServicePoint ServicePoint { get; }
Timeout
Gets or sets the time (in milliseconds) to wait for the server to send the response. Inherited from WebRequest
public int Timeout { get; set; }
TransferEncoding
Gets or sets the value of the Transfer-Encoding HTTP header.
public System.Net.TransferEncoding TransferEncoding { get; set; }
Url
Gets or sets the Uri to which the request is sent.
public Uri Url { get; set; }
UserAgent
Gets or sets the value of the User-Agent HTTP header.
public string UserAgent { get; set; }
Methods
Abort()
Aborts the current asynchronous request to a resource. Inherited from WebRequest
public virtual void Abort();
GetRequestStream()
Returns a Stream object that you can use to send data to the server.
public virtual System.IO.Stream GetRequestStream();
GetRequestStreamAsync()
Returns a task that represents the asynchronous operation.
public virtual System.Threading.Tasks.TaskSystem.IO.Stream> GetRequestStreamAsync();
GetResponse()
Sends the request to the server and waits for a response.
public virtual System.Net.WebResponse GetResponse();
GetResponseAsync()
Returns a task that represents the asynchronous operation.
public virtual System.Threading.Tasks.TaskSystem.Net.WebResponse> GetResponseAsync();