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

WebRequest是的abstract基类。用于从 Internet 访问数据的网络请求/响应模型。WebRequest is the abstract base class for .NET's request/response model for accessing data from the Internet. 使用请求/响应模型的应用程序可以采用与协议无关的方式从 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.

在访问 Internet 资源的过程中发生错误时, WebRequest类将引发。 WebExceptionThe WebRequest class throws a WebException when errors occur while accessing an Internet resource. 属性是指示错误源的WebExceptionStatus值之一。 StatusThe Status property is one of the WebExceptionStatus values that indicates the source of the error. StatusWebExceptionStatus.ProtocolErrorWebResponseResponse属性包含从 Internet 资源接收的。When Status is WebExceptionStatus.ProtocolError, the Response property contains the WebResponse received from the Internet resource.

由于类是类,因此Create ,运行时实例的实际行为由方法返回的子代类确定。WebRequest abstract WebRequestBecause 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. 有关默认值和异常的详细信息,请参阅子代类的文档,例如HttpWebRequest和。 FileWebRequestFor more information about default values and exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.

备注

使用方法初始化新WebRequest实例。 CreateUse 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从继承时,必须重写以下成员: PreAuthenticate ContentType Headers ContentLength Method RequestUri、、、、 GetRequestStream() 、、EndGetRequestStream(IAsyncResult) 、、、 BeginGetRequestStream(AsyncCallback, Object) CredentialsGetResponse()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)

WebRequestSerializationInfo 类的指定实例初始化 StreamingContext 类的新实例。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 类派生的工厂对象,该类用于创建为生成对指定 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

当在子类中被重写时,获取或设置用于对 Internet 资源请求进行身份验证的网络凭据。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 代理。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

当在子类中被重写时,获取或设置用于访问此 Internet 资源的网络代理。When overridden in a descendant class, gets or sets the network proxy to use to access this Internet resource.

RequestUri RequestUri RequestUri RequestUri

当在子类中被重写时,获取与请求关联的 Internet 资源的 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)

当在子类中被重写时,开始对 Internet 资源的异步请求。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)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。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)

当在子类中重写时,返回用于将数据写入 Internet 资源的 StreamWhen 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()

检索控制此实例的生存期策略的当前生存期服务对象。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()

当在子类中重写时,返回用于将数据写入 Internet 资源的 StreamWhen overridden in a descendant class, returns a Stream for writing data to the Internet resource.

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

当在子类中被重写时,将用于写入数据的 Stream 作为异步操作返回到 Internet 资源。When overridden in a descendant class, returns a Stream for writing data to the Internet resource as an asynchronous operation.

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

当在子类中被重写时,返回对 Internet 请求的响应。When overridden in a descendant class, returns a response to an Internet request.

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

当在子类中被重写时,将作为异步操作返回对 Internet 请求的响应。When overridden in a descendant class, returns a response to an Internet request as an asynchronous operation.

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

返回当前模拟用户的 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 的浅表副本。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.

适用于

另请参阅