WebRequest 類別

定義

對統一資源識別元 (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
[<System.Serializable>]
type WebRequest = class
    inherit MarshalByRefObject
    interface ISerializable
Public MustInherit Class WebRequest
Public MustInherit Class WebRequest
Inherits MarshalByRefObject
Implements ISerializable
繼承
WebRequest
繼承
衍生
屬性
實作

範例

下列範例示範如何建立 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

備註

重要

我們不建議您使用 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 基類。用來從網際網路存取資料的 NET 要求/回應模型。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 WebException 當存取網際網路資源時發生錯誤,類別會擲回。The 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.ProtocolErrorResponse 屬性會包含 WebResponse 從網際網路資源接收的。When Status is WebExceptionStatus.ProtocolError, the Response property contains the WebResponse received from the Internet resource.

因為 WebRequest 類別是 abstract 類別,所以 WebRequest 在執行時間實際的實例行為是由方法所傳回的子代類別所決定 CreateBecause 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.

注意

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

注意

如果建立 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.

給實施者的注意事項

當您繼承自時 WebRequest ,您必須覆寫下列成員: MethodRequestUriHeadersContentLength 、、、 ContentType Credentials PreAuthenticate GetRequestStream() 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). 您必須 IWebRequestCreate 使用 RegisterPrefix(String, IWebRequestCreate) 方法或設定檔案來註冊實介面的類別。You must register the class that implements the IWebRequestCreate interface, using the RegisterPrefix(String, IWebRequestCreate) method or the configuration file.

建構函式

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.

屬性

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.

方法

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.

(繼承來源 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.

(繼承來源 Object)
GetHashCode()

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

(繼承來源 Object)
GetLifetimeService()
已過時。

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

(繼承來源 MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext)

將序列化目標物件所需的資料填入 SerializationInfoPopulates 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.

(繼承來源 Object)
InitializeLifetimeService()
已過時。

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

(繼承來源 MarshalByRefObject)
MemberwiseClone()

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

(繼承來源 Object)
MemberwiseClone(Boolean)

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

(繼承來源 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.

(繼承來源 Object)

明確介面實作

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

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

適用於

另請參閱