WebRequest WebRequest WebRequest WebRequest Class

Definition

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

public ref class WebRequest abstract : MarshalByRefObject, System::Runtime::Serialization::ISerializable
[Serializable]
public abstract class WebRequest : MarshalByRefObject, System.Runtime.Serialization.ISerializable
type WebRequest = class
    inherit MarshalByRefObject
    interface ISerializable
Public MustInherit Class WebRequest
Inherits MarshalByRefObject
Implements ISerializable
Inheritance
Derived
Attributes
SerializableAttribute
Implements

Examples

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

#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();
}

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

Remarks

Important

We don't recommend that you use WebRequest or its derived classes for new development. Instead, use the System.Net.Http.HttpClient class.

WebRequest is the abstract base class for .NET'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.

Note

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

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(AsyncCallback, Object), EndGetRequestStream(IAsyncResult), GetResponse(), BeginGetResponse(AsyncCallback, Object), and EndGetResponse(IAsyncResult). In addition, you must provide an implementation of the IWebRequestCreate interface, which defines the Create(Uri) method used when you call Create(Uri). You must register the class that implements the IWebRequestCreate interface, using the RegisterPrefix(String, IWebRequestCreate) method or the configuration file.

Constructors

WebRequest() WebRequest() WebRequest() WebRequest()

Initializes a new instance of the WebRequest class.

WebRequest(SerializationInfo, StreamingContext) WebRequest(SerializationInfo, StreamingContext) WebRequest(SerializationInfo, StreamingContext) WebRequest(SerializationInfo, StreamingContext)

Initializes a new instance of the WebRequest class from the specified instances of the SerializationInfo and StreamingContext classes.

Properties

AuthenticationLevel AuthenticationLevel AuthenticationLevel AuthenticationLevel

Gets or sets values indicating the level of authentication and impersonation used for this request.

CachePolicy CachePolicy CachePolicy CachePolicy

Gets or sets the cache policy for this request.

ConnectionGroupName ConnectionGroupName ConnectionGroupName ConnectionGroupName

When overridden in a descendant class, gets or sets the name of the connection group for the request.

ContentLength ContentLength ContentLength ContentLength

When overridden in a descendant class, gets or sets the content length of the request data being sent.

ContentType ContentType ContentType ContentType

When overridden in a descendant class, gets or sets the content type of the request data being sent.

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

Credentials Credentials Credentials Credentials

When overridden in a descendant class, gets or sets the network credentials used for authenticating the request with the Internet resource.

DefaultCachePolicy DefaultCachePolicy DefaultCachePolicy DefaultCachePolicy

Gets or sets the default cache policy for this request.

DefaultWebProxy DefaultWebProxy DefaultWebProxy DefaultWebProxy

Gets or sets the global HTTP proxy.

Headers Headers Headers Headers

When overridden in a descendant class, gets or sets the collection of header name/value pairs associated with the request.

ImpersonationLevel ImpersonationLevel ImpersonationLevel ImpersonationLevel

Gets or sets the impersonation level for the current request.

Method Method Method Method

When overridden in a descendant class, gets or sets the protocol method to use in this request.

PreAuthenticate PreAuthenticate PreAuthenticate PreAuthenticate

When overridden in a descendant class, indicates whether to pre-authenticate the request.

Proxy Proxy Proxy Proxy

When overridden in a descendant class, gets or sets the network proxy to use to access this Internet resource.

RequestUri RequestUri RequestUri RequestUri

When overridden in a descendant class, gets the URI of the Internet resource associated with the request.

Timeout Timeout Timeout Timeout

Gets or sets the length of time, in milliseconds, before the request times out.

UseDefaultCredentials UseDefaultCredentials UseDefaultCredentials UseDefaultCredentials

When overridden in a descendant class, gets or sets a Boolean value that controls whether DefaultCredentials are sent with requests.

Methods

Abort() Abort() Abort() Abort()

Aborts the request.

BeginGetRequestStream(AsyncCallback, Object) BeginGetRequestStream(AsyncCallback, Object) BeginGetRequestStream(AsyncCallback, Object) BeginGetRequestStream(AsyncCallback, Object)

When overridden in a descendant class, provides an asynchronous version of the GetRequestStream() method.

BeginGetResponse(AsyncCallback, Object) BeginGetResponse(AsyncCallback, Object) BeginGetResponse(AsyncCallback, Object) BeginGetResponse(AsyncCallback, Object)

When overridden in a descendant class, begins an asynchronous request for an Internet resource.

Create(String) Create(String) Create(String) Create(String)

Initializes a new WebRequest instance for the specified URI scheme.

Create(Uri) Create(Uri) Create(Uri) Create(Uri)

Initializes a new WebRequest instance for the specified URI scheme.

CreateDefault(Uri) CreateDefault(Uri) CreateDefault(Uri) CreateDefault(Uri)

Initializes a new WebRequest instance for the specified URI scheme.

CreateHttp(String) CreateHttp(String) CreateHttp(String) CreateHttp(String)

Initializes a new HttpWebRequest instance for the specified URI string.

CreateHttp(Uri) CreateHttp(Uri) CreateHttp(Uri) CreateHttp(Uri)

Initializes a new HttpWebRequest instance for the specified URI.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
EndGetRequestStream(IAsyncResult) EndGetRequestStream(IAsyncResult) EndGetRequestStream(IAsyncResult) EndGetRequestStream(IAsyncResult)

When overridden in a descendant class, returns a Stream for writing data to the Internet resource.

EndGetResponse(IAsyncResult) EndGetResponse(IAsyncResult) EndGetResponse(IAsyncResult) EndGetResponse(IAsyncResult)

When overridden in a descendant class, returns a WebResponse.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo with the data needed to serialize the target object.

GetRequestStream() GetRequestStream() GetRequestStream() GetRequestStream()

When overridden in a descendant class, returns a Stream for writing data to the Internet resource.

GetRequestStreamAsync() GetRequestStreamAsync() GetRequestStreamAsync() GetRequestStreamAsync()

When overridden in a descendant class, returns a Stream for writing data to the Internet resource as an asynchronous operation.

GetResponse() GetResponse() GetResponse() GetResponse()

When overridden in a descendant class, returns a response to an Internet request.

GetResponseAsync() GetResponseAsync() GetResponseAsync() GetResponseAsync()

When overridden in a descendant class, returns a response to an Internet request as an asynchronous operation.

GetSystemWebProxy() GetSystemWebProxy() GetSystemWebProxy() GetSystemWebProxy()

Returns a proxy configured with the Internet Explorer settings of the currently impersonated user.

GetType() GetType() GetType() GetType()

Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
RegisterPortableWebRequestCreator(IWebRequestCreate) RegisterPortableWebRequestCreator(IWebRequestCreate) RegisterPortableWebRequestCreator(IWebRequestCreate) RegisterPortableWebRequestCreator(IWebRequestCreate)

Register an IWebRequestCreate object.

RegisterPrefix(String, IWebRequestCreate) RegisterPrefix(String, IWebRequestCreate) RegisterPrefix(String, IWebRequestCreate) RegisterPrefix(String, IWebRequestCreate)

Registers a WebRequest descendant for the specified URI.

ToString() ToString() ToString() ToString()

Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext)

When overridden in a descendant class, populates a SerializationInfo instance with the data needed to serialize the WebRequest.

Security

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

Applies to

See Also