Export (0) Print
Expand All
Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

HttpWebRequest Class

July 28, 2014

Provides an HTTP-specific implementation of the WebRequest class.

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

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

public class HttpWebRequest : WebRequest

The HttpWebRequest type exposes the following members.

  NameDescription
Protected methodHttpWebRequestInitializes a new instance of the HttpWebRequest class.
Top

  NameDescription
Public propertyAcceptGets or sets the value of the Accept HTTP header.
Public propertyAllowAutoRedirectGets or sets a value that indicates whether the request should follow redirection responses.
Public propertyAllowReadStreamBufferingWhen overridden in a descendant class, gets or sets a value that indicates whether to buffer the data read from the Internet resource.
Public propertyAllowWriteStreamBufferingGets or sets a value that indicates whether to buffer the data sent to the Internet resource.
Public propertyContentLengthGets for sets the length, in bytes, of content sent by the client. (Overrides WebRequest.ContentLength.)
Public propertyContentTypeGets or sets the value of the Content-type HTTP header. (Overrides WebRequest.ContentType.)
Public propertyContinueTimeoutGets or sets a timeout, in milliseconds, to wait until the 100-Continue is received from the server.
Public propertyCookieContainerSpecifies the collection of CookieCollection objects associated with the HTTP request.
Public propertyCreatorInstanceWhen 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 propertyCredentialsGets or sets authentication information for the request. (Overrides WebRequest.Credentials.)
Public propertyHaveResponseGets a value that indicates whether a response has been received from an Internet resource.
Public propertyHeadersSpecifies a collection of the name/value pairs that make up the HTTP headers. (Overrides WebRequest.Headers.)
Public propertyMethodGets or sets the method for the request. (Overrides WebRequest.Method.)
Public propertyRequestUriGets the original Uniform Resource Identifier (URI) of the request. (Overrides WebRequest.RequestUri.)
Public propertySupportsCookieContainerGets a value that indicates whether the CookieContainer property is supported by the HttpWebRequest instance.
Public propertyUseDefaultCredentialsGets or sets a Boolean value that controls whether default credentials are sent with requests. (Overrides WebRequest.UseDefaultCredentials.)
Public propertyUserAgentGets or sets the value of the User-agent HTTP header.
Top

  NameDescription
Public methodAbortCancels a request to an Internet resource. (Overrides WebRequest.Abort().)
Public methodBeginGetRequestStreamBegins an asynchronous request for a Stream object to use to write data. (Overrides WebRequest.BeginGetRequestStream(AsyncCallback, Object).)
Public methodBeginGetResponseBegins an asynchronous request to an Internet resource. (Overrides WebRequest.BeginGetResponse(AsyncCallback, Object).)
Public methodEndGetRequestStreamEnds an asynchronous request for a Stream object to use to write data. (Overrides WebRequest.EndGetRequestStream(IAsyncResult).)
Public methodEndGetResponseEnds an asynchronous request to an Internet resource. (Overrides WebRequest.EndGetResponse(IAsyncResult).)
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeReleases the resources held by the current HttpWebRequest instance. (Overrides Object.Finalize().)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetRequestStreamAsyncWhen overridden in a descendent class, returns a Stream for writing data to the Internet resource as an asynchronous operation. (Overrides WebRequest.GetRequestStreamAsync().)
Public methodGetResponseAsyncWhen overridden in a descendant class, returns a response to an Internet request as an asynchronous operation. (Overrides WebRequest.GetResponseAsync().)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Public Extension MethodGetCurrentNetworkInterfaceGets all available information about the network interface that corresponds to a web request. (Defined by WebRequestExtensions.)
Public Extension MethodSetNetworkPreferenceSets the preference for a web request to use either cellular or non-cellular technology. (Defined by WebRequestExtensions.)
Public Extension MethodSetNetworkRequirementSets the requirement for a web request to use either cellular or non-cellular technology. (Defined by WebRequestExtensions.)
Top

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.

NoteNote:

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.


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("http://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);
      }
  }


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

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

Show:
© 2014 Microsoft