WebRequest WebRequest WebRequest WebRequest Class

定義

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

public ref class WebRequest abstract : MarshalByRefObject, System::Runtime::Serialization::ISerializable
[System.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
繼承
衍生
屬性
實作

範例

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

備註

重要

我們不建議您改用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.

WebRequestabstract基底類別。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. StatusWebExceptionStatus.ProtocolError,則Response屬性包含WebResponse接收自網際網路資源。When 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.

注意

使用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,您必須覆寫下列成員: 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). 您必須註冊類別,可實作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() WebRequest() WebRequest()

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

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

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

屬性

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

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

取得或設定全域 HTTP Proxy。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

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

RequestUri RequestUri RequestUri RequestUri

在子代類別中覆寫時,取得與要求相關聯的網際網路資源 URI。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

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

方法

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

中止要求。Aborts the request.

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

在子代類別中覆寫時,會提供 GetRequestStream() 方法的非同步版本。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)

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

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

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

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

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

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

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

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

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

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) 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) EndGetRequestStream(IAsyncResult) EndGetRequestStream(IAsyncResult) EndGetRequestStream(IAsyncResult)

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

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

在子代類別中覆寫時,傳回 WebResponseWhen 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()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。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)

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

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

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

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

在子代類別中覆寫時,傳回用來將資料寫入網際網路資源的 Stream,做為非同步作業。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()

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

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

取得目前執行個體的 TypeGets 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()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

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

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

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

註冊 IWebRequestCreate 物件。Register an IWebRequestCreate object.

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

登錄指定 URI 的 WebRequest 子代。Registers a WebRequest descendant for the specified URI.

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

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

(Inherited from Object)

明確介面實作

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

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

安全性

WebPermission
若要存取要求的 URI 或任何要求重新導向的 URI。To access the requested URI or any URI that the request is redirected to. 關聯的列舉型別:ConnectAssociated enumeration: Connect.

適用於

另請參閱