HttpWebRequest Class

[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]

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

Public Class HttpWebRequest _
    Inherits WebRequest
public class HttpWebRequest : WebRequest

The HttpWebRequest type exposes the following members.

Constructors

  Name Description
HttpWebRequest Initializes a new instance of the HttpWebRequest class.

Top

Properties

  Name Description
Accept Gets or sets the value of the Accept HTTP header.
AllowAutoRedirect Gets or sets a value that indicates whether the request should follow redirection responses.
AllowReadStreamBuffering When overridden in a descendant class, gets or sets a value that indicates whether to buffer the data read from the Internet resource.
AllowWriteStreamBuffering Gets or sets a value that indicates whether to buffer the data sent to the Internet resource.
ContentLength Gets for sets the length, in bytes, of content sent by the client. (Overrides WebRequest..::.ContentLength.)
ContentType Gets or sets the value of the Content-type HTTP header. (Overrides WebRequest..::.ContentType.)
ContinueTimeout Gets or sets a timeout, in milliseconds, to wait until the 100-Continue is received from the server.
CookieContainer Specifies the collection of CookieCollection objects associated with the HTTP request.
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.)
Credentials Gets or sets authentication information for the request. (Overrides WebRequest..::.Credentials.)
HaveResponse Gets a value that indicates whether a response has been received from an Internet resource.
Headers Specifies a collection of the name/value pairs that make up the HTTP headers. (Overrides WebRequest..::.Headers.)
Method Gets or sets the method for the request. (Overrides WebRequest..::.Method.)
RequestUri Gets the original Uniform Resource Identifier (URI) of the request. (Overrides WebRequest..::.RequestUri.)
SupportsCookieContainer Gets a value that indicates whether the CookieContainer property is supported by the HttpWebRequest instance.
UseDefaultCredentials Gets or sets a Boolean value that controls whether default credentials are sent with requests. (Overrides WebRequest..::.UseDefaultCredentials.)
UserAgent Gets or sets the value of the User-agent HTTP header.

Top

Methods

  Name Description
Abort Cancels a request to an Internet resource. (Overrides WebRequest..::.Abort()()().)
BeginGetRequestStream Begins an asynchronous request for a Stream object to use to write data. (Overrides WebRequest..::.BeginGetRequestStream(AsyncCallback, Object).)
BeginGetResponse Begins an asynchronous request to an Internet resource. (Overrides WebRequest..::.BeginGetResponse(AsyncCallback, Object).)
EndGetRequestStream Ends an asynchronous request for a Stream object to use to write data. (Overrides WebRequest..::.EndGetRequestStream(IAsyncResult).)
EndGetResponse Ends an asynchronous request to an Internet resource. (Overrides WebRequest..::.EndGetResponse(IAsyncResult).)
Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Finalize Releases the resources held by the current HttpWebRequest instance. (Overrides Object..::.Finalize()()().)
GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
GetRequestStreamAsync When overridden in a descendent class, returns a Stream for writing data to the Internet resource as an asynchronous operation. (Overrides WebRequest..::.GetRequestStreamAsync()()().)
GetResponseAsync When overridden in a descendant class, returns a response to an Internet request as an asynchronous operation. (Overrides WebRequest..::.GetResponseAsync()()().)
GetType Gets the Type of the current instance. (Inherited from Object.)
MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
ToString Returns a string that represents the current object. (Inherited from Object.)

Top

Extension Methods

  Name Description
GetCurrentNetworkInterface Gets all available information about the network interface that corresponds to a web request. (Defined by WebRequestExtensions.)
SetNetworkPreference Sets the preference for a web request to use either cellular or non-cellular technology. (Defined by WebRequestExtensions.)
SetNetworkRequirement Sets the requirement for a web request to use either cellular or non-cellular technology. (Defined by WebRequestExtensions.)

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 Referer header is properly set on all HTTP requests applicable to client HTTP handling for ClientHttp.

The Item property can be used to set custom headers.

If the local 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.

Note

For security reasons, cookies are disabled by default.

Support for cross-domain connectivity allows an application to access resources from locations other than the site of origin. This is an important feature for enabling applications to consume existing services on the web.

The security policy system 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, access is restricted to certain classes of URLs from the WebClient and HTTP classes in the System.Net namespace. There are similar access restrictions applied to other classes including the Image and MediaElement classes in the System.Windows.Controls namespace. Access restrictions are also applied 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 security reasons, the HttpWebRequest class is restricted 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.

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

Capabilities

If you use this API in your app, you must specify the following capabilities in the app manifest. Otherwise, your app might not work correctly or it might exit unexpectedly.

ID_CAP_NETWORKING

Windows Phone 8, Windows Phone OS 7.1

For more info, see App capabilities and hardware requirements for Windows Phone 8.

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);

          allDone.WaitOne();

          // Release the HttpWebResponse resource.
          myRequestState.response.Close();
      }
      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
          // ...

          Debug.WriteLine(e.Message);
      }
  }

  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
          // ...

          Debug.WriteLine(e.Message);
      }
  }

Version Information

Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Platforms

Windows Phone

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

System.Net Namespace