HttpWebRequest Class (System.Net)

Switch View :
ScriptFree
.NET Framework Class Library
HttpWebRequest Class

Provides an HTTP-specific implementation of the WebRequest class.

Inheritance Hierarchy

System.Object
  System.MarshalByRefObject
    System.Net.WebRequest
      System.Net.HttpWebRequest

Namespace:  System.Net
Assembly:  System (in System.dll)
Syntax

Visual Basic
<SerializableAttribute> _
Public Class HttpWebRequest _
	Inherits WebRequest _
	Implements ISerializable
C#
[SerializableAttribute]
public class HttpWebRequest : WebRequest, 
	ISerializable
Visual C++
[SerializableAttribute]
public ref class HttpWebRequest : public WebRequest, 
	ISerializable
F#
[<SerializableAttribute>]
type HttpWebRequest =  
    class
        inherit WebRequest
        interface ISerializable
    end

The HttpWebRequest type exposes the following members.

Constructors

  Name Description
Protected method HttpWebRequest Obsolete. Initializes a new instance of the HttpWebRequest class from the specified instances of the SerializationInfo and StreamingContext classes.
Top
Properties

  Name Description
Public property Supported by Portable Class Library Accept Gets or sets the value of the Accept HTTP header.
Public property Address Gets the Uniform Resource Identifier (URI) of the Internet resource that actually responds to the request.
Public property AllowAutoRedirect Gets or sets a value that indicates whether the request should follow redirection responses.
Public property AllowWriteStreamBuffering Gets or sets a value that indicates whether to buffer the data sent to the Internet resource.
Public property AuthenticationLevel Gets or sets values indicating the level of authentication and impersonation used for this request. (Inherited from WebRequest.)
Public property AutomaticDecompression Gets or sets the type of decompression that is used.
Public property CachePolicy Gets or sets the cache policy for this request. (Inherited from WebRequest.)
Public property ClientCertificates Gets or sets the collection of security certificates that are associated with this request.
Public property Connection Gets or sets the value of the Connection HTTP header.
Public property ConnectionGroupName Gets or sets the name of the connection group for the request. (Overrides WebRequest.ConnectionGroupName.)
Public property ContentLength Gets or sets the Content-length HTTP header. (Overrides WebRequest.ContentLength.)
Public property Supported by Portable Class Library ContentType Gets or sets the value of the Content-type HTTP header. (Overrides WebRequest.ContentType.)
Public property ContinueDelegate Gets or sets the delegate method called when an HTTP 100-continue response is received from the Internet resource.
Public property Supported by Portable Class Library CookieContainer Gets or sets the cookies associated with the request.
Public property Credentials Gets or sets authentication information for the request. (Overrides WebRequest.Credentials.)
Public property Date Get or set the Date HTTP header value to use in an HTTP request.
Public property Static member DefaultCachePolicy Gets or sets the default cache policy for this request.
Public property Static member DefaultMaximumErrorResponseLength Gets or sets the default maximum length of an HTTP error response.
Public property Static member DefaultMaximumResponseHeadersLength Gets or sets the default for the MaximumResponseHeadersLength property.
Public property Expect Gets or sets the value of the Expect HTTP header.
Public property Supported by Portable Class Library HaveResponse Gets a value that indicates whether a response has been received from an Internet resource.
Public property Supported by Portable Class Library Headers Specifies a collection of the name/value pairs that make up the HTTP headers. (Overrides WebRequest.Headers.)
Public property Host Get or set the Host header value to use in an HTTP request independent from the request URI.
Public property IfModifiedSince Gets or sets the value of the If-Modified-Since HTTP header.
Public property ImpersonationLevel Gets or sets the impersonation level for the current request. (Inherited from WebRequest.)
Public property KeepAlive Gets or sets a value that indicates whether to make a persistent connection to the Internet resource.
Public property MaximumAutomaticRedirections Gets or sets the maximum number of redirects that the request follows.
Public property MaximumResponseHeadersLength Gets or sets the maximum allowed length of the response headers.
Public property MediaType Gets or sets the media type of the request.
Public property Supported by Portable Class Library Method Gets or sets the method for the request. (Overrides WebRequest.Method.)
Public property Pipelined Gets or sets a value that indicates whether to pipeline the request to the Internet resource.
Public property PreAuthenticate Gets or sets a value that indicates whether to send an Authorization header with the request. (Overrides WebRequest.PreAuthenticate.)
Public property ProtocolVersion Gets or sets the version of HTTP to use for the request.
Public property Proxy Gets or sets proxy information for the request. (Overrides WebRequest.Proxy.)
Public property ReadWriteTimeout Gets or sets a time-out in milliseconds when writing to or reading from a stream.
Public property Referer Gets or sets the value of the Referer HTTP header.
Public property Supported by Portable Class Library RequestUri Gets the original Uniform Resource Identifier (URI) of the request. (Overrides WebRequest.RequestUri.)
Public property SendChunked Gets or sets a value that indicates whether to send data in segments to the Internet resource.
Public property ServicePoint Gets the service point to use for the request.
Public property Supported by Portable Class Library SupportsCookieContainer
Public property Timeout Gets or sets the time-out value in milliseconds for the GetResponse and GetRequestStream methods. (Overrides WebRequest.Timeout.)
Public property TransferEncoding Gets or sets the value of the Transfer-encoding HTTP header.
Public property UnsafeAuthenticatedConnectionSharing Gets or sets a value that indicates whether to allow high-speed NTLM-authenticated connection sharing.
Public property UseDefaultCredentials Gets or sets a Boolean value that controls whether default credentials are sent with requests. (Overrides WebRequest.UseDefaultCredentials.)
Public property UserAgent Gets or sets the value of the User-agent HTTP header.
Top
Methods

  Name Description
Public method Supported by Portable Class Library Abort Cancels a request to an Internet resource. (Overrides WebRequest.Abort.)
Public method AddRange(Int32) Adds a byte range header to a request for a specific range from the beginning or end of the requested data.
Public method AddRange(Int64) Adds a byte range header to a request for a specific range from the beginning or end of the requested data.
Public method AddRange(Int32, Int32) Adds a byte range header to the request for a specified range.
Public method AddRange(Int64, Int64) Adds a byte range header to the request for a specified range.
Public method AddRange(String, Int32) Adds a Range header to a request for a specific range from the beginning or end of the requested data.
Public method AddRange(String, Int64) Adds a Range header to a request for a specific range from the beginning or end of the requested data.
Public method AddRange(String, Int32, Int32) Adds a range header to a request for a specified range.
Public method AddRange(String, Int64, Int64) Adds a range header to a request for a specified range.
Public method Supported by Portable Class Library BeginGetRequestStream Begins an asynchronous request for a Stream object to use to write data. (Overrides WebRequest.BeginGetRequestStream(AsyncCallback, Object).)
Public method Supported by Portable Class Library BeginGetResponse Begins an asynchronous request to an Internet resource. (Overrides WebRequest.BeginGetResponse(AsyncCallback, Object).)
Public method CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public method Supported by Portable Class Library EndGetRequestStream(IAsyncResult) Ends an asynchronous request for a Stream object to use to write data. (Overrides WebRequest.EndGetRequestStream(IAsyncResult).)
Public method EndGetRequestStream(IAsyncResult, TransportContext) Ends an asynchronous request for a Stream object to use to write data and outputs the TransportContext associated with the stream.
Public method Supported by Portable Class Library EndGetResponse Ends an asynchronous request to an Internet resource. (Overrides WebRequest.EndGetResponse(IAsyncResult).)
Public method Supported by Portable Class Library Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Supported by Portable Class Library Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Supported by Portable Class Library GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method GetObjectData Infrastructure. Populates a SerializationInfo with the data required to serialize the target object. (Overrides WebRequest.GetObjectData(SerializationInfo, StreamingContext).)
Public method GetRequestStream Gets a Stream object to use to write request data. (Overrides WebRequest.GetRequestStream.)
Public method GetRequestStream(TransportContext) Gets a Stream object to use to write request data and outputs the TransportContext associated with the stream.
Public method GetResponse Returns a response from an Internet resource. (Overrides WebRequest.GetResponse.)
Public method Supported by Portable Class Library GetType Gets the Type of the current instance. (Inherited from Object.)
Public method InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method Supported by Portable Class Library MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public method Supported by Portable Class Library ToString Returns a string that represents the current object. (Inherited from Object.)
Top
Explicit Interface Implementations

  Name Description
Explicit interface implemetation Private method ISerializable.GetObjectData Infrastructure. Populates a SerializationInfo with the data needed to serialize the target object.
Top
Remarks

The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP.

Do not use the HttpWebRequest constructor. Use the WebRequest.Create method to initialize new HttpWebRequest objects. If the scheme for the Uniform Resource Identifier (URI) is http:// or https://, Create returns an HttpWebRequest object.

The GetResponse method makes a synchronous request to the resource specified in the RequestUri property and returns an HttpWebResponse that contains the response. You can make an asynchronous request to the resource using the BeginGetResponse and EndGetResponse methods.

When you want to send data to the resource, the GetRequestStream method returns a Stream object to use to send data. The BeginGetRequestStream and EndGetRequestStream methods provide asynchronous access to the send data stream.

For client authentication with HttpWebRequest, the client certificate must be installed in the My certificate store of the current user.

The HttpWebRequest class throws a WebException when errors occur while accessing a resource. The WebException.Status property contains a WebExceptionStatus value that indicates the source of the error. When WebException.Status is WebExceptionStatus.ProtocolError, the Response property contains the HttpWebResponse received from the resource.

HttpWebRequest exposes common HTTP header values sent to the Internet resource as properties, set by methods, or set by the system; the following table contains a complete list. You can set other headers in the Headers property as name/value pairs. Note that servers and caches may change or add headers during the request.

The following table lists the HTTP headers that are set either by properties or methods or the system.

Header

Set by

Accept

Set by the Accept property.

Connection

Set by the Connection property, KeepAlive property.

Content-Length

Set by the ContentLength property.

Content-Type

Set by the ContentType property.

Expect

Set by the Expect property.

Date

Set by the system to current date.

Host

Set by the system to current host information.

If-Modified-Since

Set by the IfModifiedSince property.

Range

Set by the AddRange method.

Referer

Set by the Referer property.

Transfer-Encoding

Set by the TransferEncoding property (the SendChunked property must be true).

User-Agent

Set by the UserAgent property.

Note Note

HttpWebRequest is registered automatically. You do not need to call the RegisterPrefix method to register System.Net.HttpWebRequest before using URIs beginning with http:// or https://.

The local computer or application config file may specify that a default proxy be used. If the Proxy property is specified, then the proxy settings from the Proxy property override the local computer or application config file and the HttpWebRequest instance will use the proxy settings specified. If no proxy is specified in a config file and the Proxy property is unspecified, the HttpWebRequest class uses the proxy settings inherited from Internet Explorer on the local computer. If there are no proxy settings in Internet Explorer, the request is sent directly to the server.

The HttpWebRequest class parses a proxy bypass list with wildcard characters inherited from Internet Explorer differently than the bypass list is parsed directly by Internet Explorer. For example, the HttpWebRequest class will parse a bypass list of "nt*" from Internet Explorer as a regular expression of "nt.$". This differs from the native behavior of Internet Explorer. So a URL of "http://intxxxxx" would bypass the proxy using the HttpWebRequest class, but would not bypass the proxy using Internet Explorer.

The HttpWebRequest class contains new members when it is used in a Portable Class Library project. For more information, see API Differences in Portable Class Library.

Note Note

The Framework caches SSL sessions as they are created and attempts to reuse a cached session for a new request, if possible. When attempting to reuse an SSL session, the Framework uses the first element of ClientCertificates (if there is one), or tries to reuse an anonymous sessions if ClientCertificates is empty.

Note Note

For security reasons, cookies are disabled by default. If you want to use cookies, use the CookieContainer property to enable cookies.

Performance Issues

A number of elements can have an impact on performance when using the HttpWebRequest class. These include the following:

  1. The ServicePointManager class.

  2. The DefaultConnectionLimit property.

  3. The UseNagleAlgorithm property.

The ServicePointManager is an object that provides connection management for HTTP connections. The ServicePointManager is a static class that creates maintains and deletes instances of the ServicePoint class. Each ServicePoint instance handles or manages connections to Internet resources based on the host Uri. After the first connection made to a host Uri, each subsequent request will use the information provided by the ServicePoint instance.

ServicePoint mySP = ServicePointManager.FindServicePoint(myUri);

The DefaultConnectionLimit property allows an application to specify how many concurrent connections should be allowed to any given resource. An application using a HttpWebRequest instance is able to specify the maximum number of concurrent persistent connections that it will have to a server. By default this is property is set to 2. So when the ServicePointManager creates a ServicePoint instance, it will assign the ConnectionLimit property to the value of the DefaultConnectionLimit property that is set on the ServicePointManager class.

The best value for the DefaultConnectionLimit property depends on the application workload and proxy settings. A general recommendation when only connecting to a few hosts or connecting through a proxy is to use a value that is 12 times the number of CPUs on the local computer. So for a computer with 4 CPUs using a proxy, the recommended value would be 48.

ServicePointManager.DefaultConnectionLimit = 48;

An application should increase the value for the DefaultConnectionLimit property under the following conditions:

  1. If the application uses a proxy.

  2. If the application primarily sends data and connects to a small number of servers.

  3. If the application connects to systems that have high latency.

An application should decrease the value for the DefaultConnectionLimit property under the following conditions:

  1. If the application is memory or resource constrained.

Another option that can have an impact on performance is the use of the UseNagleAlgorithm property. When this property is set to true, TCP/IP will try to use the TCP Nagle algorithm for HTTP connections. The Nagle algorithm aggregates data when sending TCP packets. It accumulates sequences of small messages into larger TCP packets before the data is sent over the network. Using the Nagle algorithm can optimize the use of network resources, although in some situations performance can also be degraded. Generally for constant high-volume throughput, a performance improvement is realized using the Nagle algorithm. But for smaller throughput applications, degradation in performance may be seen.

An application doesn't normally need to change the default value for the UseNagleAlgorithm property which is set to true. However, if an application is using low-latency connections, it may help to set this property to false.

ServicePointManager.UseNagleAlgorithm = false;

Examples

The following code example creates an HttpWebRequest for the URI http://www.contoso.com/.

Visual Basic


        Dim myReq As HttpWebRequest = _
            WebRequest.Create("http://www.contoso.com/")



C#


HttpWebRequest myReq =
(HttpWebRequest)WebRequest.Create("http://www.contoso.com/");



Visual C++

HttpWebRequest^ myReq = dynamic_cast<HttpWebRequest^>(WebRequest::Create( "http://www.contoso.com/" ));


Version Information

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library
.NET Framework Security

  • WebPermission  

    to access the requested URI or any URI that the request is redirected to. Associated enumeration: Connect

Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
See Also

Reference

Other Resources

Community Content

DennisSk
HttpOnly cookies in WP7 Explained

Recently I had a mystery with HttpOnly cookies in WP7. It seemed like they disappeared magically from the response header in a httpWebReqeust.
 
Using this code firing at some one issuing a HttpCookie:

    

   CookieContainer cookieJar = new CookieContainer();
   private void FireRequest()
   {
            var request = HttpWebRequest.Create(new Uri("http://www.google.se")) as HttpWebRequest;
 
            request.Method = "GET";
            request.CookieContainer = cookieJar;
 
            request.BeginGetResponse(ar =>
            {
                HttpWebRequest req2 = (HttpWebRequest)ar.AsyncState;
                var response = (HttpWebResponse)req2.EndGetResponse(ar);
                int numVisibleCookies = response.Cookies.Count;
 
            }, request);
        }

 Inspecting the response.Cookies.Count would only reveal  1 cookie, eventhou my Fiddler capture suggested two! It was clear to me that the HttpOnly attribute on the second cookie, made it invisible!
 
Headers captured with Fiddler (see instructions here: http://phone7.wordpress.com/2010/10/17/fiddler-and-wp7-emulator-working/
 

HTTP/1.1 200 OK
Date: Wed, 28 Sep 2011 07:18:28 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
Server: gws
X-XSS-Protection: 1; mode=block
Transfer-Encoding: chunked
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Set-Cookie: PREF=ID=730e57a63c8afc7d:FF=0:TM=1317194308:LM=1317194308:S=OjVtq8VJG4RUFtHq; expires=Fri, 27-Sep-2013 07:18:28 GMT; path=/; domain=.google.se
Set-Cookie: NID=51=kXqGUUCG_z11Gu2XWpfDtvYJ6B1YB4r4tcYVH2NoZ90GqkZdAdHz9-DhRv5KcxrMmjmWF6efjMedinc3xSh5RwI8ffzmkdBrSJIpQ4QlDsX5Wsb8yB9UbgxhCQ6lLhmY; expires=Thu, 29-Mar-2012 07:18:28 GMT; path=/; domain=.google.se; HttpOnly
Age: 0

 
But looking at response.Cookies.count only shows one cookie!
 
At first I was sure the WP7 framework actually filtered out the header and threw it away. However, it dawned on me that the CookieContainer actually protected the Cookie not letting me see it! So, updating the code slightly to produce two calls and then inspect the headers again:

        CookieContainer cookieJar = new CookieContainer();
        int count = 0;
        private void FireRequest()
        {
            var request = HttpWebRequest.Create(new Uri("http://www.google.se")) as HttpWebRequest;

            request.Method = "GET";
            request.CookieContainer = cookieJar;

            request.BeginGetResponse(ar =>
            {
                HttpWebRequest req2 = (HttpWebRequest)ar.AsyncState;
                var response = (HttpWebResponse)req2.EndGetResponse(ar);
                int numVisibleCookies = response.Cookies.Count;

                // Now Fire again and inspect cookie.
                count++;
                if (count < 2)
                {
                    // Now just fire another request to inspect headers
                    FireRequest();
                }

            }, request);
        }

 
Inspecting the captured headers in Fiddler, shows us that httpWebRequest actually sends two cookies in the second request… AS LONG AS you make sure to hold on to your CookieContainer and re use the same one on the second call!
 
First request: Headers Received: (removed noise)

HTTP/1.1 200 OK
Set-Cookie: PREF=ID=730e57a63c8afc7d:FF=0:TM=1317194308:LM=1317194308:S=OjVtq8VJG4RUFtHq; expires=Fri, 27-Sep-2013 07:18:28 GMT; path=/; domain=.google.se
Set-Cookie: NID=51=kXqGUUCG_z11Gu2XWpfDtvYJ6B1YB4r4tcYVH2NoZ90GqkZdAdHz9-DhRv5KcxrMmjmWF6efjMedinc3xSh5RwI8ffzmkdBrSJIpQ4QlDsX5Wsb8yB9UbgxhCQ6lLhmY; expires=Thu, 29-Mar-2012 07:18:28 GMT; path=/; domain=.google.se; HttpOnly

 
Second request, Headers sent:

GET http://www.google.se/ HTTP/1.1
Accept: */*
Referer: file:///Applications/Install/4AC5F2A5-C382-41C9-ADD0-1F5E368D541F/Install/
Accept-Encoding: identity
Cookie: PREF=ID=730e57a63c8afc7d:FF=0:TM=1317194308:LM=1317194308:S=OjVtq8VJG4RUFtHq; NID=51=kXqGUUCG_z11Gu2XWpfDtvYJ6B1YB4r4tcYVH2NoZ90GqkZdAdHz9-DhRv5KcxrMmjmWF6efjMedinc3xSh5RwI8ffzmkdBrSJIpQ4QlDsX5Wsb8yB9UbgxhCQ6lLhmY
User-Agent: NativeHost
Host: www.google.se
Proxy-Connection: Keep-Alive

And there was the proof that eventhou we could not see the cookies in the response.Cookies collection, they are in the container, and actually got sent on the second request!


CouldYouMakeHelpingYouAnyMorePainful
Unable To Serialize

Curious thing that all my attempts to serialize an instance of this class result in:

Type 'System.Net.WebRequest+WebProxyWrapper' in Assembly 'System, 
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked 
as serializable.

Sample code:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://big.URL.here");
IFormatter formatter = new BinaryFormatter();
MemoryStream msRequest = new MemoryStream();
formatter.Serialize(msRequest, request);

PetSerAl
Misprint
"nt.$" -> "nt.*"