WebRequest Class

Definition

對統一資源識別元 (URI) 提出要求。Makes a request to a Uniform Resource Identifier (URI). 這是 abstract 類別。This is an abstract class.

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

Examples

下列範例顯示如何建立 WebRequest 實例,並傳迴響應。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.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
    End Class
End Namespace

Remarks

Important

我們不建議您使用 WebRequest 或其衍生類別來進行新的開發。We don't recommend that you use WebRequest or its derived classes for new development. 請改用 System.Net.Http.HttpClient 類別。Instead, use the System.Net.Http.HttpClient class.

WebRequest 是的 abstract 基類。用來從網際網路存取資料的網路要求/回應模型。WebRequest is the abstract base class for .NET's request/response model for accessing data from the Internet. 使用要求/回應模型的應用程式可以用不限通訊協定的方式從網際網路要求資料,其中應用程式會使用 WebRequest 類別的實例,而通訊協定特定的子代類別則會執行要求的詳細資料。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.

要求會從應用程式傳送到特定的 URI,例如伺服器上的網頁。Requests are sent from an application to a particular URI, such as a Web page on a server. URI 會從為應用程式註冊的 WebRequest 子代清單中,決定要建立的適當子代類別。The URI determines the proper descendant class to create from a list of WebRequest descendants registered for the application. WebRequest 子系通常會註冊來處理特定的通訊協定(例如 HTTP 或 FTP),但是可以註冊以處理對伺服器上特定伺服器或路徑的要求。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.

當存取網際網路資源時發生錯誤時,WebRequest 類別會擲回 WebExceptionThe WebRequest class throws a WebException when errors occur while accessing an Internet resource. Status 屬性是指出錯誤來源的其中一個 WebExceptionStatus 值。The Status property is one of the WebExceptionStatus values that indicates the source of the error. Status WebExceptionStatus.ProtocolError時,Response 屬性會包含從網際網路資源接收的 WebResponseWhen Status is WebExceptionStatus.ProtocolError, the Response property contains the WebResponse received from the Internet resource.

因為 WebRequest 類別是 abstract 類別,所以在執行時間 WebRequest 實例的實際行為是由 Create 方法所傳回的子代類別所決定。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. 如需預設值和例外狀況的詳細資訊,請參閱子代類別的檔,例如 HttpWebRequestFileWebRequestFor more information about default values and exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.

Note

使用 Create 方法來初始化新的 WebRequest 實例。Use the Create method to initialize new WebRequest instances. 請勿使用 WebRequest 的函式。Do not use the WebRequest constructor.

Note

如果建立 WebRequest 物件的應用程式以一般使用者的認證執行,應用程式將無法存取本機電腦存放區中安裝的憑證,除非使用者已明確授與許可權。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 Implementers

當您從 WebRequest繼承時,必須覆寫下列成員: MethodRequestUriHeadersContentLengthContentTypeCredentialsPreAuthenticateGetRequestStream()BeginGetRequestStream(AsyncCallback, Object)EndGetRequestStream(IAsyncResult)GetResponse()BeginGetResponse(AsyncCallback, Object)EndGetResponse(IAsyncResult)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). 此外,您還必須提供 IWebRequestCreate 介面的執行,這會定義當您呼叫 Create(Uri)時所使用的 Create(Uri) 方法。In addition, you must provide an implementation of the IWebRequestCreate interface, which defines the Create(Uri) method used when you call Create(Uri). 您必須使用 RegisterPrefix(String, IWebRequestCreate) 方法或設定檔,註冊用來執行 IWebRequestCreate 介面的類別。You must register the class that implements the IWebRequestCreate interface, using the RegisterPrefix(String, IWebRequestCreate) method or the configuration file.

Constructors

WebRequest()

WebRequest 類別的新執行個體初始化。Initializes a new instance of the WebRequest class.

WebRequest(SerializationInfo, StreamingContext)

初始化 WebRequest 類別的新執行個體,這個執行個體是來自 SerializationInfoStreamingContext 類別的指定執行個體。Initializes a new instance of the WebRequest class from the specified instances of the SerializationInfo and StreamingContext classes.

Properties

AuthenticationLevel

取得或設定值,指出用於這個要求的驗證和模擬等級。Gets or sets values indicating the level of authentication and impersonation used for this request.

CachePolicy

取得或設定這個要求的快取原則。Gets or sets the cache policy for this request.

ConnectionGroupName

在子代類別中覆寫時,取得或設定要求的連接群組名稱。When overridden in a descendant class, gets or sets the name of the connection group for the request.

ContentLength

在子代類別中覆寫時,取得或設定正在傳送要求資料的內容長度。When overridden in a descendant class, gets or sets the content length of the request data being sent.

ContentType

在子代類別中覆寫時,取得或設定正在傳送要求資料的內容類型。When overridden in a descendant class, gets or sets the content type of the request data being sent.

CreatorInstance

在子代類別中覆寫時,取得衍生自 IWebRequestCreate 類別的 Factory 物件,用來建立執行個體化的 WebRequest 以對指定的 URI 提出要求。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

在子代類別中覆寫時,取得或設定使用網際網路資源驗證要求的網路認證。When overridden in a descendant class, gets or sets the network credentials used for authenticating the request with the Internet resource.

DefaultCachePolicy

取得或設定這個要求的預設快取原則。Gets or sets the default cache policy for this request.

DefaultWebProxy

取得或設定全域 HTTP Proxy。Gets or sets the global HTTP proxy.

Headers

在子代類別中覆寫時,取得或設定與要求相關聯的標頭名稱/值組集合。When overridden in a descendant class, gets or sets the collection of header name/value pairs associated with the request.

ImpersonationLevel

取得或設定目前要求的模擬等級。Gets or sets the impersonation level for the current request.

Method

在子代類別中覆寫時,取得或設定這個要求中要使用的通訊協定方法。When overridden in a descendant class, gets or sets the protocol method to use in this request.

PreAuthenticate

在子代類別中覆寫時,指出是否要預先驗證要求。When overridden in a descendant class, indicates whether to pre-authenticate the request.

Proxy

在子代類別中覆寫時,取得或設定要用來存取這個網際網路資源的網路 Proxy。When overridden in a descendant class, gets or sets the network proxy to use to access this Internet resource.

RequestUri

在子代類別中覆寫時,取得與要求相關聯的網際網路資源 URI。When overridden in a descendant class, gets the URI of the Internet resource associated with the request.

Timeout

取得或設定要求逾時之前的時間長度 (以毫秒為單位)。Gets or sets the length of time, in milliseconds, before the request times out.

UseDefaultCredentials

在子代類別中覆寫時,取得或設定 Boolean 值,控制 DefaultCredentials 是否隨著要求傳送。When overridden in a descendant class, gets or sets a Boolean value that controls whether DefaultCredentials are sent with requests.

Methods

Abort()

中止要求。Aborts the request.

BeginGetRequestStream(AsyncCallback, Object)

在子代類別中覆寫時,會提供 GetRequestStream() 方法的非同步版本。When overridden in a descendant class, provides an asynchronous version of the GetRequestStream() method.

BeginGetResponse(AsyncCallback, Object)

在子代類別中覆寫時,開始網際網路資源的非同步要求。When overridden in a descendant class, begins an asynchronous request for an Internet resource.

Create(String)

為指定的 URI 配置,初始化新的 WebRequest 執行個體。Initializes a new WebRequest instance for the specified URI scheme.

Create(Uri)

為指定的 URI 配置,初始化新的 WebRequest 執行個體。Initializes a new WebRequest instance for the specified URI scheme.

CreateDefault(Uri)

為指定的 URI 配置,初始化新的 WebRequest 執行個體。Initializes a new WebRequest instance for the specified URI scheme.

CreateHttp(String)

為指定的 URI 字串,初始化新的 HttpWebRequest 執行個體。Initializes a new HttpWebRequest instance for the specified URI string.

CreateHttp(Uri)

為指定的 URI 配置,初始化新的 HttpWebRequest 執行個體。Initializes a new HttpWebRequest instance for the specified URI.

CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。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)

在子代類別中覆寫時,傳回 Stream,以便將資料寫入至網際網路資源。When overridden in a descendant class, returns a Stream for writing data to the Internet resource.

EndGetResponse(IAsyncResult)

在子代類別中覆寫時,傳回 WebResponseWhen overridden in a descendant class, returns a WebResponse.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext)

SerializationInfo 中填入序列化目標物件所需的資料。Populates a SerializationInfo with the data needed to serialize the target object.

GetRequestStream()

在子代類別中覆寫時,傳回 Stream,以便將資料寫入至網際網路資源。When overridden in a descendant class, returns a Stream for writing data to the Internet resource.

GetRequestStreamAsync()

在子代類別中覆寫時,傳回以非同步作業方式將資料寫入網際網路資源的 StreamWhen overridden in a descendant class, returns a Stream for writing data to the Internet resource as an asynchronous operation.

GetResponse()

在子代類別中覆寫時,傳回對網際網路要求的回應。When overridden in a descendant class, returns a response to an Internet request.

GetResponseAsync()

在子代類別中覆寫時,傳回對網際網路要求的回應,做為非同步作業。When overridden in a descendant class, returns a response to an Internet request as an asynchronous operation.

GetSystemWebProxy()

傳回 Proxy,其組態為目前模擬使用者的 Internet Explorer 設定。Returns a proxy configured with the Internet Explorer settings of the currently impersonated user.

GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService()

取得存留期服務物件,以控制這個執行個體的存留期原則。Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
RegisterPortableWebRequestCreator(IWebRequestCreate)

註冊 IWebRequestCreate 物件。Register an IWebRequestCreate object.

RegisterPrefix(String, IWebRequestCreate)

註冊指定 URI 的 WebRequest 子代。Registers a WebRequest descendant for the specified URI.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

在子代類別中覆寫時,以序列化 WebRequest 所需的資料填入 SerializationInfo 執行個體。When overridden in a descendant class, populates a SerializationInfo instance with the data needed to serialize the WebRequest.

Applies to

See also