Share via


HttpWebRequest Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Provides an HTTP-specific implementation of the WebRequest class.

Inheritance Hierarchy

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

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

Syntax

'Declaration
Public MustInherit Class HttpWebRequest _
    Inherits WebRequest
public abstract class HttpWebRequest : WebRequest

The HttpWebRequest type exposes the following members.

Constructors

  Name Description
Protected methodSupported by Silverlight for Windows Phone HttpWebRequest Initializes a new instance of the HttpWebRequest class.

Top

Properties

  Name Description
Public propertySupported by Silverlight for Windows Phone Accept Gets or sets the value of the Accept HTTP header.
Public propertySupported by Silverlight for Windows Phone AllowAutoRedirect Gets or sets a value that indicates whether the request should follow redirection responses.
Public propertySupported by Silverlight for Windows Phone AllowReadStreamBuffering When overridden in a descendant class, gets or sets a value that indicates whether to buffer the data read from the Internet resource.
Public property AllowWriteStreamBuffering When overridden in a descendant class, gets or sets a value that indicates whether to buffer the data written to the Internet resource.
Public property ContentLength When overridden in a descendant class, gets or sets the content length of the request data being sent. (Inherited from WebRequest.)
Public propertySupported by Silverlight for Windows Phone ContentType Gets or sets the value of the Content-type HTTP header. (Overrides WebRequest.ContentType.)
Public propertySupported by Silverlight for Windows Phone CookieContainer Specifies the collection of CookieCollection objects associated with the HTTP request.
Public propertySupported by Silverlight for Windows Phone CreatorInstance When overridden in a descendant class, gets the factory object derived from the IWebRequestCreate class used to create the WebRequest instantiated for making the request to the specified URI. (Inherited from WebRequest.)
Public propertySupported by Silverlight for Windows Phone Credentials When overridden in a descendant class, gets or sets the network credentials used for authenticating the request with the Internet resource. (Inherited from WebRequest.)

In Silverlight for Windows Phone, this member is overridden by Credentials.

In XNA Framework, this member is overridden by Credentials.
Public propertySupported by Silverlight for Windows Phone HaveResponse Gets a value that indicates whether a response has been received from an Internet resource.
Public propertySupported by Silverlight for Windows Phone Headers Specifies a collection of the name/value pairs that make up the HTTP headers. (Overrides WebRequest.Headers.)
Public propertySupported by Silverlight for Windows Phone Method Gets or sets the method for the request. (Overrides WebRequest.Method.)
Public propertySupported by Silverlight for Windows Phone RequestUri Gets the original Uniform Resource Identifier (URI) of the request. (Overrides WebRequest.RequestUri.)
Public propertySupported by Silverlight for Windows Phone SupportsCookieContainer Gets a value that indicates whether the CookieContainer property is supported by the HttpWebRequest instance.
Public propertySupported by Silverlight for Windows Phone UseDefaultCredentials When overridden in a descendant class, gets or sets a Boolean value that controls whether default credentials are sent with requests. (Inherited from WebRequest.)
Public propertySupported by Silverlight for Windows Phone UserAgent Gets or sets the value of the User-agent HTTP header.

Top

Methods

  Name Description
Public methodSupported by Silverlight for Windows Phone Abort Cancels a request to an Internet resource. (Overrides WebRequest.Abort().)
Public methodSupported by Silverlight for Windows Phone BeginGetRequestStream Begins an asynchronous request for a Stream object to use to write data. (Overrides WebRequest.BeginGetRequestStream(AsyncCallback, Object).)
Public methodSupported by Silverlight for Windows Phone BeginGetResponse Begins an asynchronous request to an Internet resource. (Overrides WebRequest.BeginGetResponse(AsyncCallback, Object).)
Public methodSupported by Silverlight for Windows Phone EndGetRequestStream Ends an asynchronous request for a Stream object to use to write data. (Overrides WebRequest.EndGetRequestStream(IAsyncResult).)
Public methodSupported by Silverlight for Windows Phone EndGetResponse Ends an asynchronous request to an Internet resource. (Overrides WebRequest.EndGetResponse(IAsyncResult).)
Public methodSupported by Silverlight for Windows Phone Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows Phone Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)

In Silverlight for Windows Phone, this member is overridden by Finalize().

In XNA Framework, this member is overridden by Finalize().
Public methodSupported by Silverlight for Windows Phone GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone GetType Gets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows Phone MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone ToString Returns a string that represents the current object. (Inherited from 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://, WebRequest.Create returns an HttpWebRequest object.

You can make an asynchronous request to the resource using the BeginGetResponse and EndGetResponse methods.

The BeginGetRequestStream and EndGetRequestStream methods provide asynchronous access to the send data stream.

The HttpWebRequest class throws a WebException when an error occurs while accessing a resource. The WebException.Status property contains a WebExceptionStatus value that indicates the source of the error.

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.

Important noteImportant Note:

Silverlight for Windows Phone In Silverlight for Windows Phone the list of headers that can be set is slightly different. For more information see Networking in Silverlight for Windows Phone.

Header

Set by

Accept

Set by the web browser that hosts the Silverlight application.

Connection

Set by the web browser that hosts the Silverlight application.

Content-Length

On Silverlight 4, set by the ContentLength property. On the browser HTTP stack, the ContentLength property is not required to be set because the Silverlight runtime will automatically populate the header with the correct value based on the buffered request body. If a Silverlight application on either the browser or client HTTP stack sets this property to a value that does not match the size of the provided request body, a ProtocolViolationException is thrown when the request is sent. 

On Silverlight 3, set by the web browser that hosts the Silverlight application.

Content-Type

Set by the ContentType property. This header cannot be set on a GET method. If this header is set, a ProtocolViolationException is thrown.

Expect

Set by the web browser that hosts the Silverlight application.

If-Modified-Since

Set by the web browser that hosts the Silverlight application.

Referer

Set by the web browser that hosts the Silverlight application.

Transfer-Encoding

Set by the web browser that hosts the Silverlight application.

User-Agent

Set by the web browser that hosts the Silverlight application.

The Mozilla FireFox browser does not currently set the Referer header on HTTP GET requests. The Internet Explorer and Safari web browsers do properly set the Referer header on HTTP GET requests. As a result, a Silverlight application hosted in Firefox can't support the Referer header being set on any GET requests applicable to browser HTTP handling for BrowserHttp. The Referer header is properly set on HTTP POST requests by Firefox, Internet Explorer, and Safari applicable to browser HTTP handling for BrowserHttp.

The Referer header is properly set on all HTTP requests applicable to client HTTP handling for ClientHttp regardless of the web browser.

The Item property can be used to set custom headers.

If the local computer configuration specifies that a proxy be used, or if the request specifies a proxy, the request is sent using the proxy. If no proxy is specified, the request is sent to the server.

NoteNote:

For security reasons, cookies are disabled by default.

Silverlight 2 and later includes support for cross-domain connectivity which allows an application to access resources from locations other than the site of origin. This is an important feature for enabling Silverlight applications to consume existing services on the web.

The security policy system in the Silverlight runtime requires that a policy file be downloaded from a network resource before a network connection is allowed access to that resource. This security policy system affects cross-domain network access for WebClient and HTTP classes in the System.Net namespace. Network connections for WebClient and HTTP classes to the site or host of origin do not require a security policy. 

For security reasons, the Silverlight runtime restricts access to certain classes of URLs from the WebClient and HTTP classes in the System.Net namespace. There are similar access restrictions applied by the Silverlight runtime to other classes including the Image and MediaElement classes in the System.Windows.Controls namespace. The Silverlight runtime also applies access restrictions to XAML source files and font files based on the class of URL.

The connections affected are access to cross-zone, cross-domain, and cross-scheme URLs. These restrictions are designed to prevent networking threats (for example, threats based on a Silverlight application run from an internet server getting access to resources on a local intranet server). For more information, see Network Security Access Restrictions in Silverlight and URL Access Restrictions in Silverlight.

For security reasons, the Silverlight runtime restricts the HttpWebRequest class from sending specific headers to a cross-domain site unless the header is allowed by the security policy applicable to the target cross-domain site. This restriction applies to resources from locations other than the site of origin. The Authorization header can be set using the Headers property. However to set the credentials properly, the cross-domain policy applicable to the target must have the http-request-headers set to allow the Authorization header to be sent.

Version Notes

Silverlight for Windows Phone Silverlight for Windows Phone

 This type is not abstract in Silverlight for Windows Phone.

Six active Web service connections are allowed simultaneously. Additional requests are paused until a connection is available.

Examples

public class RequestState
{
  // This class stores the State of the request.
  const int BUFFER_SIZE = 1024;
  public StringBuilder requestData;
  public byte[] BufferRead;
  public HttpWebRequest request;
  public HttpWebResponse response;
  public Stream streamResponse;

  public RequestState()
  {
    BufferRead = new byte[BUFFER_SIZE];
    requestData = new StringBuilder("");
    request = null;
    streamResponse = null;
  }
}

public class Example
{

  public static ManualResetEvent allDone= new ManualResetEvent(false);
  const int BUFFER_SIZE = 1024;

  public static void Demo(System.Windows.Controls.TextBlock outputBlock)
  {
  try
  {      

    System.Uri uri = new Uri("https://www.contoso.com");
    // Create a HttpWebrequest object to the desired URL.
    HttpWebRequest myHttpWebRequest1= (HttpWebRequest)WebRequest.Create(uri);

    // Create an instance of the RequestState and assign the previous myHttpWebRequest1
    // object to it's request field.  
    RequestState myRequestState = new RequestState();  
    myRequestState.request = myHttpWebRequest1;


    // Start the asynchronous request.
    IAsyncResult result=
      (IAsyncResult) myHttpWebRequest1.BeginGetResponse(new AsyncCallback(RespCallback),myRequestState);

  }
  catch(WebException e)
  {
    outputBlock.Text += "\nException raised!\n";
    outputBlock.Text += "Message: ";
    outputBlock.Text += e.Message;
    outputBlock.Text += "\nStatus: ";
    outputBlock.Text += e.Status;
    outputBlock.Text += "\n";
  }
  catch(Exception e)
  {
    outputBlock.Text += "\nException raised!\n";
    outputBlock.Text += "\nMessage: ";
    outputBlock.Text += e.Message;
    outputBlock.Text += "\n";
  }
}
private static void RespCallback(IAsyncResult asynchronousResult)
{  
  try
  {
    // State of request is asynchronous.
    RequestState myRequestState=(RequestState) asynchronousResult.AsyncState;
    HttpWebRequest  myHttpWebRequest2=myRequestState.request;
    myRequestState.response = (HttpWebResponse) myHttpWebRequest2.EndGetResponse(asynchronousResult);

    // Read the response into a Stream object.
    Stream responseStream = myRequestState.response.GetResponseStream();
    myRequestState.streamResponse=responseStream;

    // Begin the Reading of the contents of the HTML page and print it to the console.
    IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
  }
  catch(WebException e)
  {
    // Need to handle the exception
  }
}
private static  void ReadCallBack(IAsyncResult asyncResult)
{
  try
  {

    RequestState myRequestState = (RequestState)asyncResult.AsyncState;
    Stream responseStream = myRequestState.streamResponse;
    int read = responseStream.EndRead( asyncResult );
    // Read the HTML page and then do something with it
    if (read > 0)
    {
      myRequestState.requestData.Append(Encoding.UTF8.GetString(myRequestState.BufferRead, 0, read));
      IAsyncResult asynchronousResult = responseStream.BeginRead( myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
    }
    else
    {
      if(myRequestState.requestData.Length>1)
      {
        string stringContent;
        stringContent = myRequestState.requestData.ToString();
        // do something with the response stream here
      }

      responseStream.Close();
      allDone.Set();

    }

  }
  catch(WebException e)
  {
    // Need to handle the exception
  }

}

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

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.