WebRequest Class (System.Net)

Switch View :
ScriptFree
.NET Framework Class Library
WebRequest Class

Makes a request to a Uniform Resource Identifier (URI). This is an abstract class.

Inheritance Hierarchy

System.Object
  System.MarshalByRefObject
    System.Net.WebRequest
      System.IO.Packaging.PackWebRequest
      System.Net.FileWebRequest
      System.Net.FtpWebRequest
      System.Net.HttpWebRequest

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

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

The WebRequest type exposes the following members.

Constructors

  Name Description
Protected method Supported by Portable Class Library WebRequest() Initializes a new instance of the WebRequest class.
Protected method WebRequest(SerializationInfo, StreamingContext) Initializes a new instance of the WebRequest class from the specified instances of the SerializationInfo and StreamingContext classes.
Top
Properties

  Name Description
Public property AuthenticationLevel Gets or sets values indicating the level of authentication and impersonation used for this request.
Public property CachePolicy Gets or sets the cache policy for this request.
Public property ConnectionGroupName When overridden in a descendant class, gets or sets the name of the connection group for the request.
Public property ContentLength When overridden in a descendant class, gets or sets the content length of the request data being sent.
Public property Supported by Portable Class Library ContentType When overridden in a descendant class, gets or sets the content type of the request data being sent.
Public property Supported by Portable Class Library Credentials When overridden in a descendant class, gets or sets the network credentials used for authenticating the request with the Internet resource.
Public property Static member DefaultCachePolicy Gets or sets the default cache policy for this request.
Public property Static member DefaultWebProxy Gets or sets the global HTTP proxy.
Public property Supported by Portable Class Library Headers When overridden in a descendant class, gets or sets the collection of header name/value pairs associated with the request.
Public property ImpersonationLevel Gets or sets the impersonation level for the current request.
Public property Supported by Portable Class Library Method When overridden in a descendant class, gets or sets the protocol method to use in this request.
Public property PreAuthenticate When overridden in a descendant class, indicates whether to pre-authenticate the request.
Public property Proxy When overridden in a descendant class, gets or sets the network proxy to use to access this Internet resource.
Public property Supported by Portable Class Library RequestUri When overridden in a descendant class, gets the URI of the Internet resource associated with the request.
Public property Timeout Gets or sets the length of time, in milliseconds, before the request times out.
Public property Supported by Portable Class Library UseDefaultCredentials When overridden in a descendant class, gets or sets a Boolean value that controls whether DefaultCredentials are sent with requests.
Top
Methods

  Name Description
Public method Supported by Portable Class Library Abort Aborts the Request
Public method Supported by Portable Class Library BeginGetRequestStream When overridden in a descendant class, provides an asynchronous version of the GetRequestStream method.
Public method Supported by Portable Class Library BeginGetResponse When overridden in a descendant class, begins an asynchronous request for an Internet resource.
Public method Static member Supported by Portable Class Library Create(String) Initializes a new WebRequest instance for the specified URI scheme.
Public method Static member Supported by Portable Class Library Create(Uri) Initializes a new WebRequest instance for the specified URI scheme.
Public method Static member CreateDefault Initializes a new WebRequest instance for the specified URI scheme.
Public method Static member Supported by Portable Class Library CreateHttp(String)
Public method Static member Supported by Portable Class Library CreateHttp(Uri)
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 When overridden in a descendant class, returns a Stream for writing data to the Internet resource.
Public method Supported by Portable Class Library EndGetResponse When overridden in a descendant class, returns a WebResponse.
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 needed to serialize the target object.
Public method GetRequestStream When overridden in a descendant class, returns a Stream for writing data to the Internet resource.
Public method GetResponse When overridden in a descendant class, returns a response to an Internet request.
Public method Static member GetSystemWebProxy Returns a proxy configured with the Internet Explorer settings of the currently impersonated user.
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 Static member Supported by Portable Class Library RegisterPrefix Registers a WebRequest descendant for the specified URI.
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. When overridden in a descendant class, populates a SerializationInfo instance with the data needed to serialize the WebRequest.
Top
Remarks

WebRequest is the abstract base class for the .NET Framework's request/response model for accessing data from the Internet. An application that uses the request/response model can request data from the Internet in a protocol-agnostic manner, in which the application works with instances of the WebRequest class while protocol-specific descendant classes carry out the details of the request.

Requests are sent from an application to a particular URI, such as a Web page on a server. The URI determines the proper descendant class to create from a list of WebRequest descendants registered for the application. WebRequest descendants are typically registered to handle a specific protocol, such as HTTP or FTP, but can be registered to handle a request to a specific server or path on a server.

The WebRequest class throws a WebException when errors occur while accessing an Internet resource. The Status property is one of the WebExceptionStatus values that indicates the source of the error. When Status is WebExceptionStatus.ProtocolError, the Response property contains the WebResponse received from the Internet resource.

Because the WebRequest class is an abstract class, the actual behavior of WebRequest instances at run time is determined by the descendant class returned by Create method. For more information about default values and exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.

The WebRequest 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

Use the Create method to initialize new WebRequest instances. Do not use the WebRequest constructor.

Note Note

If the application that creates the WebRequest object runs with the credentials of a Normal user, the application will not be able to access certificates installed in the local machine store unless permission has been explicitly given to the user to do so.

Notes to Inheritors

When you inherit from WebRequest, you must override the following members: Method, RequestUri, Headers, ContentLength, ContentType, Credentials, PreAuthenticate, GetRequestStream, BeginGetRequestStream, EndGetRequestStream, GetResponse, BeginGetResponse, and EndGetResponse. In addition, you must provide an implementation of the IWebRequestCreate interface, which defines the Create method used when you call Create. You must register the class that implements the IWebRequestCreate interface, using the RegisterPrefix method or the configuration file.

Examples

The following example shows how to create a WebRequest instance and return the response.

Visual Basic

Imports System
Imports System.IO
Imports System.Net
Imports System.Text
Namespace Examples.System.Net
    Public Class WebRequestGetExample

        Public Shared Sub Main()
            ' Create a request for the URL. 		
            Dim request As WebRequest = WebRequest.Create("http://www.contoso.com/default.html")
            ' If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials
            ' Get the response.
            Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
            ' Display the status.
            Console.WriteLine(response.StatusDescription)
            ' Get the stream containing content returned by the server.
            Dim dataStream As Stream = response.GetResponseStream()
            ' Open the stream using a StreamReader for easy access.
            Dim reader As New StreamReader(dataStream)
            ' Read the content.
            Dim responseFromServer As String = reader.ReadToEnd()
            ' Display the content.
            Console.WriteLine(responseFromServer)
            ' Cleanup the streams and the response.
            reader.Close()
            dataStream.Close()
            response.Close()
        End Sub 'Main
    End Class 'WebRequestGetExample
End Namespace


C#

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Create a request for the URL. 		
            WebRequest request = WebRequest.Create ("http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
            // Display the status.
            Console.WriteLine (response.StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream ();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader (dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd ();
            // Display the content.
            Console.WriteLine (responseFromServer);
            // Cleanup the streams and the response.
            reader.Close ();
            dataStream.Close ();
            response.Close ();
        }
    }
}


Visual C++

#using <System.dll>

using namespace System;
using namespace System::IO;
using namespace System::Net;
using namespace System::Text;
int main()
{

   // Create a request for the URL.   
   WebRequest^ request = WebRequest::Create( "http://www.contoso.com/default.html" );

   // If required by the server, set the credentials.
   request->Credentials = CredentialCache::DefaultCredentials;

   // Get the response.
   HttpWebResponse^ response = dynamic_cast<HttpWebResponse^>(request->GetResponse());

   // Display the status.
   Console::WriteLine( response->StatusDescription );

   // Get the stream containing content returned by the server.
   Stream^ dataStream = response->GetResponseStream();

   // Open the stream using a StreamReader for easy access.
   StreamReader^ reader = gcnew StreamReader( dataStream );

   // Read the content.
   String^ responseFromServer = reader->ReadToEnd();

   // Display the content.
   Console::WriteLine( responseFromServer );

   // Cleanup the streams and the response.
   reader->Close();
   dataStream->Close();
   response->Close();
}



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