HttpWebRequest 类

定义

提供 WebRequest 类的 HTTP 特定的实现。Provides an HTTP-specific implementation of the WebRequest class.

public ref class HttpWebRequest : System::Net::WebRequest, System::Runtime::Serialization::ISerializable
[System.Serializable]
public class HttpWebRequest : System.Net.WebRequest, System.Runtime.Serialization.ISerializable
type HttpWebRequest = class
    inherit WebRequest
    interface ISerializable
Public Class HttpWebRequest
Inherits WebRequest
Implements ISerializable
继承
属性
实现

示例

下面的代码示例创建 URI http://www.contoso.com/HttpWebRequestThe following code example creates an HttpWebRequest for the URI http://www.contoso.com/.

HttpWebRequest^ myReq = dynamic_cast<HttpWebRequest^>(WebRequest::Create( "http://www.contoso.com/" ));

HttpWebRequest myReq =
(HttpWebRequest)WebRequest.Create("http://www.contoso.com/");


Dim myReq As HttpWebRequest = _
    WebRequest.Create("http://www.contoso.com/")

注解

重要

建议不要将 HttpWebRequest 用于新的开发。We don't recommend that you use HttpWebRequest for new development. 请改用 System.Net.Http.HttpClient 类。Instead, use the System.Net.Http.HttpClient class.

HttpWebRequest 类为 WebRequest 中定义的属性和方法提供支持,并提供其他属性和方法,使用户能够使用 HTTP 直接与服务器交互。The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP.

不要使用 HttpWebRequest 构造函数。Do not use the HttpWebRequest constructor. 使用 WebRequest.Create 方法来初始化新的 HttpWebRequest 对象。Use the WebRequest.Create method to initialize new HttpWebRequest objects. 如果统一资源标识符(URI)的方案为 http://https://,则 Create 返回 HttpWebRequest 对象。If the scheme for the Uniform Resource Identifier (URI) is http:// or https://, Create returns an HttpWebRequest object.

GetResponse 方法对 RequestUri 属性中指定的资源进行同步请求,并返回包含响应对象的 HttpWebResponseThe GetResponse method makes a synchronous request to the resource specified in the RequestUri property and returns an HttpWebResponse that contains the response object. 可以使用 GetResponseStream返回的流接收响应数据。The response data can be received by using the stream returned by GetResponseStream. 如果响应对象或响应流已关闭,则将作废剩余数据。If the response object or the response stream is closed, remaining data will be forfeited. 如果满足以下条件,则剩余的数据将被释放,并且在关闭响应对象或流时,套接字将重新用于后续请求:这是一个 keep-alive 或流水线请求,只需收到少量的数据,或在较短的时间间隔内接收剩余数据。The remaining data will be drained and the socket will be re-used for subsequent requests when closing the response object or stream if the following conditions hold: it's a keep-alive or pipelined request, only a small amount of data needs to be received, or the remaining data is received in a small time interval. 如果未满足上述条件,则将关闭套接字。If none of the mentioned conditions hold or the drain time is exceeded, the socket will be closed. 对于 keep-alive 连接或管线连接,强烈建议应用程序读取流直到 EOF。For keep-alive or pipelined connections, we strongly recommend that the application reads the streams until EOF. 这可确保在后续请求中重复使用套接字,从而提高性能并减少使用的资源。This ensures that the socket will be re-used for subsequent requests resulting in better performance and less resources used.

若要将数据发送到资源,GetRequestStream 方法返回一个用于发送数据的 Stream 对象。When you want to send data to the resource, the GetRequestStream method returns a Stream object to use to send data. BeginGetRequestStreamEndGetRequestStream 方法提供对发送数据流的异步访问。The BeginGetRequestStream and EndGetRequestStream methods provide asynchronous access to the send data stream.

对于 HttpWebRequest的客户端身份验证,客户端证书必须安装在当前用户的 "我的证书存储" 中。For client authentication with HttpWebRequest, the client certificate must be installed in the My certificate store of the current user.

当访问资源的过程中出现错误时,HttpWebRequest 类将引发 WebExceptionThe HttpWebRequest class throws a WebException when errors occur while accessing a resource. WebException.Status 属性包含一个 WebExceptionStatus 值,该值指示错误的源。The WebException.Status property contains a WebExceptionStatus value that indicates the source of the error. WebExceptionStatus.ProtocolErrorWebException.Status 时,Response 属性包含从资源接收的 HttpWebResponseWhen WebException.Status is WebExceptionStatus.ProtocolError, the Response property contains the HttpWebResponse received from the resource.

HttpWebRequest 公开作为属性、由方法设置或由系统设置的发送到 Internet 资源的常见 HTTP 标头值;下表包含一个完整的列表。HttpWebRequest exposes common HTTP header values sent to the Internet resource as properties, set by methods, or set by the system; the following table contains a complete list. 可以将 Headers 属性中的其他标头设置为名称/值对。You can set other headers in the Headers property as name/value pairs. 请注意,在请求期间服务器和缓存可能会更改或添加标头。Note that servers and caches may change or add headers during the request.

下表列出了由属性或方法或系统设置的 HTTP 标头。The following table lists the HTTP headers that are set either by properties or methods or the system.

HeaderHeader 设置者Set by
接受Accept Accept 属性设置。Set by the Accept property.
连接Connection Connection 属性设置,KeepAlive 属性。Set by the Connection property, KeepAlive property.
Content-lengthContent-Length ContentLength 属性设置。Set by the ContentLength property.
Content-TypeContent-Type ContentType 属性设置。Set by the ContentType property.
ExpectExpect Expect 属性设置。Set by the Expect property.
日期Date 由系统设置为当前日期。Set by the system to current date.
主机Host 由系统设置为当前主机信息。Set by the system to current host information.
If-Modified-SinceIf-Modified-Since IfModifiedSince 属性设置。Set by the IfModifiedSince property.
范围Range AddRange 方法设置。Set by the AddRange method.
RefererReferer Referer 属性设置。Set by the Referer property.
传输编码Transfer-Encoding TransferEncoding 属性设置(SendChunked 属性必须 true)。Set by the TransferEncoding property (the SendChunked property must be true).
User-AgentUser-Agent UserAgent 属性设置。Set by the UserAgent property.

备注

自动注册 HttpWebRequestHttpWebRequest is registered automatically. 不需要调用 RegisterPrefix 方法来注册 System.Net.HttpWebRequest,然后才能使用以 http://https://开头的 Uri。You do not need to call the RegisterPrefix method to register System.Net.HttpWebRequest before using URIs beginning with http:// or https://.

本地计算机或应用程序配置文件可以指定使用默认代理。The local computer or application config file may specify that a default proxy be used. 如果指定 Proxy 属性,则 Proxy 属性中的代理设置将覆盖本地计算机或应用程序配置文件,HttpWebRequest 实例将使用指定的代理设置。If the Proxy property is specified, then the proxy settings from the Proxy property override the local computer or application config file and the HttpWebRequest instance will use the proxy settings specified. 如果未在配置文件中指定代理,并且未指定 Proxy 属性,则 HttpWebRequest 类将使用从本地计算机上的 Internet Explorer 继承的代理设置。If no proxy is specified in a config file and the Proxy property is unspecified, the HttpWebRequest class uses the proxy settings inherited from Internet Explorer on the local computer. 如果 Internet Explorer 中没有代理设置,请求将直接发送到服务器。If there are no proxy settings in Internet Explorer, the request is sent directly to the server.

HttpWebRequest 类分析一个代理跳过列表,其中包含从 Internet Explorer 继承的通配符字符,而不是由 Internet Explorer 直接分析绕过列表。The HttpWebRequest class parses a proxy bypass list with wildcard characters inherited from Internet Explorer differently than the bypass list is parsed directly by Internet Explorer. 例如,HttpWebRequest 类会将 Internet Explorer 中的 "nt *" 跳过列表分析为 "nt. $" 的正则表达式。For example, the HttpWebRequest class will parse a bypass list of "nt*" from Internet Explorer as a regular expression of "nt.$". 这与 Internet Explorer 的本机行为不同。This differs from the native behavior of Internet Explorer. 因此,URL "http://intxxxxx" 会绕过代理使用 HttpWebRequest 类,但不会使用 Internet Explorer 来绕过代理。So a URL of "http://intxxxxx" would bypass the proxy using the HttpWebRequest class, but would not bypass the proxy using Internet Explorer.

备注

框架在创建时将缓存 SSL 会话,并在可能的情况下尝试重复使用缓存会话来执行新请求。The Framework caches SSL sessions as they are created and attempts to reuse a cached session for a new request, if possible. 尝试重用 SSL 会话时,框架使用 ClientCertificates 的第一个元素(如果有),或者如果 ClientCertificates 为空则尝试重复使用匿名会话。When attempting to reuse an SSL session, the Framework uses the first element of ClientCertificates (if there is one), or tries to reuse an anonymous sessions if ClientCertificates is empty.

备注

出于安全考虑,默认情况下会禁用 cookie。For security reasons, cookies are disabled by default. 如果要使用 cookie,请使用 CookieContainer 属性启用 cookie。If you want to use cookies, use the CookieContainer property to enable cookies.

4.6 .NET Framework 包括一项新的安全功能,用于阻止连接的不安全密码和哈希算法。The .NET Framework 4.6 includes a new security feature that blocks insecure cipher and hashing algorithms for connections. 默认情况下,通过 Api 使用 TLS/SSL (如 HttpClient、HttpWebRequest、FTPClient、System.net.mail.smtpclient、System.net.security.sslstream 等)和目标 .NET Framework 4.6 获取更安全的行为。Applications using TLS/SSL through APIs such as HttpClient, HttpWebRequest, FTPClient, SmtpClient, SslStream, etc. and targeting .NET Framework 4.6 get the more-secure behavior by default.

开发人员可能需要选择退出此行为,以便与现有的 SSL3 服务或具有 RC4 服务的 TLS 保持互操作性。Developers may want to opt out of this behavior in order to maintain interoperability with their existing SSL3 services OR TLS w/ RC4 services. 本文介绍如何修改代码,以便禁用新行为。This article explains how to modify your code so that the new behavior is disabled.

构造函数

HttpWebRequest()

初始化 HttpWebRequest 类的新实例。Initializes a new instance of the HttpWebRequest class. 此构造函数已过时。This constructor is obsolete.

HttpWebRequest(SerializationInfo, StreamingContext)

HttpWebRequestSerializationInfo 类的指定实例初始化 StreamingContext 类的新实例。Initializes a new instance of the HttpWebRequest class from the specified instances of the SerializationInfo and StreamingContext classes. 此构造函数已过时。This constructor is obsolete.

HttpWebRequest(Uri)

属性

Accept

获取或设置 Accept HTTP 标头的值。Gets or sets the value of the Accept HTTP header.

Address

获取实际响应请求的 Internet 资源的统一资源标识符 (URI)。Gets the Uniform Resource Identifier (URI) of the Internet resource that actually responds to the request.

AllowAutoRedirect

获取或设置一个值,该值指示请求是否应跟随重定向响应。Gets or sets a value that indicates whether the request should follow redirection responses.

AllowReadStreamBuffering

获取或设置一个值,该值指示是否对从 Internet 资源接收的数据进行缓冲处理。Gets or sets a value that indicates whether to buffer the received from the Internet resource.

AllowWriteStreamBuffering

获取或设置一个值,该值指示是否对发送到 Internet 资源的数据进行缓冲处理。Gets or sets a value that indicates whether to buffer the data sent to the Internet resource.

AuthenticationLevel

获取或设置用于此请求的身份验证和模拟的级别。Gets or sets values indicating the level of authentication and impersonation used for this request.

(继承自 WebRequest)
AutomaticDecompression

获取或设置所使用的解压缩类型。Gets or sets the type of decompression that is used.

CachePolicy

获取或设置此请求的缓存策略。Gets or sets the cache policy for this request.

(继承自 WebRequest)
ClientCertificates

获取或设置与此请求关联的安全证书集合。Gets or sets the collection of security certificates that are associated with this request.

Connection

获取或设置 Connection HTTP 标头的值。Gets or sets the value of the Connection HTTP header.

ConnectionGroupName

获取或设置请求的连接组的名称。Gets or sets the name of the connection group for the request.

ContentLength

获取或设置 Content-length HTTP 标头。Gets or sets the Content-length HTTP header.

ContentType

获取或设置 Content-type HTTP 标头的值。Gets or sets the value of the Content-type HTTP header.

ContinueDelegate

获取或设置当从 Internet 资源接收到 HTTP 100-continue 响应时调用的委托方法。Gets or sets the delegate method called when an HTTP 100-continue response is received from the Internet resource.

ContinueTimeout

获取或设置在接收到来自服务器的 100-Continue 之前要等待的超时(以毫秒为单位)。Gets or sets a timeout, in milliseconds, to wait until the 100-Continue is received from the server.

CookieContainer

获取或设置与此请求关联的 Cookie。Gets or sets the cookies associated with the request.

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.

(继承自 WebRequest)
Credentials

获取或设置请求的身份验证信息。Gets or sets authentication information for the request.

Date

获取或设置要在 HTTP 请求中使用的 Date HTTP 标头值。Gets or sets the Date HTTP header value to use in an HTTP request.

DefaultCachePolicy

获取或设置此请求的默认缓存策略。Gets or sets the default cache policy for this request.

DefaultMaximumErrorResponseLength

获取或设置 HTTP 错误响应的默认最大长度。Gets or sets the default maximum length of an HTTP error response.

DefaultMaximumResponseHeadersLength

获取或设置 MaximumResponseHeadersLength 属性的默认值。Gets or sets the default for the MaximumResponseHeadersLength property.

Expect

获取或设置 Expect HTTP 标头的值。Gets or sets the value of the Expect HTTP header.

HaveResponse

获取一个值,该值指示是否收到了来自 Internet 资源的响应。Gets a value that indicates whether a response has been received from an Internet resource.

Headers

指定构成 HTTP 标头的名称/值对的集合。Specifies a collection of the name/value pairs that make up the HTTP headers.

Host

获取或设置要在 HTTP 请求中独立于请求 URI 使用的 Host 标头值。Gets or sets the Host header value to use in an HTTP request independent from the request URI.

IfModifiedSince

获取或设置 If-Modified-Since HTTP 标头的值。Gets or sets the value of the If-Modified-Since HTTP header.

ImpersonationLevel

获取或设置当前请求的模拟级别。Gets or sets the impersonation level for the current request.

(继承自 WebRequest)
KeepAlive

获取或设置一个值,该值指示是否与 Internet 资源建立持续型连接。Gets or sets a value that indicates whether to make a persistent connection to the Internet resource.

MaximumAutomaticRedirections

获取或设置请求将跟随的重定向的最大数目。Gets or sets the maximum number of redirects that the request follows.

MaximumResponseHeadersLength

获取或设置响应标头允许的最大长度。Gets or sets the maximum allowed length of the response headers.

MediaType

获取或设置请求的媒体类型。Gets or sets the media type of the request.

Method

获取或设置请求的方法。Gets or sets the method for the request.

Pipelined

获取或设置一个值,该值指示是否通过管线将请求传输到 Internet 资源。Gets or sets a value that indicates whether to pipeline the request to the Internet resource.

PreAuthenticate

获取或设置一个值,该值指示是否随请求发送一个 Authorization 标头。Gets or sets a value that indicates whether to send an Authorization header with the request.

ProtocolVersion

获取或设置用于请求的 HTTP 版本。Gets or sets the version of HTTP to use for the request.

Proxy

获取或设置请求的代理信息。Gets or sets proxy information for the request.

ReadWriteTimeout

获取或设置写入或读取流时的超时(以毫秒为单位)。Gets or sets a time-out in milliseconds when writing to or reading from a stream.

Referer

获取或设置 Referer HTTP 标头的值。Gets or sets the value of the Referer HTTP header.

RequestUri

获取请求的原始统一资源标识符 (URI)。Gets the original Uniform Resource Identifier (URI) of the request.

SendChunked

获取或设置一个值,该值指示是否将数据分段发送到 Internet 资源。Gets or sets a value that indicates whether to send data in segments to the Internet resource.

ServerCertificateValidationCallback

获取或设置用于验证服务器证书的回调函数。Gets or sets a callback function to validate the server certificate.

ServicePoint

获取用于请求的服务点。Gets the service point to use for the request.

SupportsCookieContainer

获取指示请求是否为 CookieContainer 提供支持的值。Gets a value that indicates whether the request provides support for a CookieContainer.

Timeout

获取或设置 GetResponse()GetRequestStream() 方法的超时值(以毫秒为单位)。Gets or sets the time-out value in milliseconds for the GetResponse() and GetRequestStream() methods.

TransferEncoding

获取或设置 Transfer-encoding HTTP 标头的值。Gets or sets the value of the Transfer-encoding HTTP header.

UnsafeAuthenticatedConnectionSharing

获取或设置一个值,该值指示是否允许经过高速 NTLM 身份验证的连接共享。Gets or sets a value that indicates whether to allow high-speed NTLM-authenticated connection sharing.

UseDefaultCredentials

获取或设置一个 Boolean 值,该值控制是否随请求一起发送默认凭据。Gets or sets a Boolean value that controls whether default credentials are sent with requests.

UserAgent

获取或设置 User-agent HTTP 标头的值。Gets or sets the value of the User-agent HTTP header.

方法

Abort()

取消对 Internet 资源的请求。Cancels a request to an Internet resource.

AddRange(Int32)

向请求添加从请求数据的开始处或结束处的特定范围的字节范围标头。Adds a byte range header to a request for a specific range from the beginning or end of the requested data.

AddRange(Int32, Int32)

向请求添加指定范围的字节范围标头。Adds a byte range header to the request for a specified range.

AddRange(Int64)

向请求添加从请求数据的开始处或结束处的特定范围的字节范围标头。Adds a byte range header to a request for a specific range from the beginning or end of the requested data.

AddRange(Int64, Int64)

向请求添加指定范围的字节范围标头。Adds a byte range header to the request for a specified range.

AddRange(String, Int32)

向请求添加从请求数据的开始处或结束处计算的特定范围的 Range 标头。Adds a Range header to a request for a specific range from the beginning or end of the requested data.

AddRange(String, Int32, Int32)

向请求添加指定范围的范围标头。Adds a range header to a request for a specified range.

AddRange(String, Int64)

向请求添加从请求数据的开始处或结束处计算的特定范围的 Range 标头。Adds a Range header to a request for a specific range from the beginning or end of the requested data.

AddRange(String, Int64, Int64)

向请求添加指定范围的范围标头。Adds a range header to a request for a specified range.

BeginGetRequestStream(AsyncCallback, Object)

开始对用于写入数据的 Stream 对象执行异步请求。Begins an asynchronous request for a Stream object to use to write data.

BeginGetResponse(AsyncCallback, Object)

开始对 Internet 资源的异步请求。Begins an asynchronous request to an Internet resource.

CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。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 对象的异步请求。Ends an asynchronous request for a Stream object to use to write data.

EndGetRequestStream(IAsyncResult, TransportContext)

结束对用于写入数据的 Stream 对象的异步请求,并输出与该流关联的 TransportContextEnds an asynchronous request for a Stream object to use to write data and outputs the TransportContext associated with the stream.

EndGetResponse(IAsyncResult)

结束对 Internet 资源的异步请求。Ends an asynchronous request to an Internet resource.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetHashCode()

返回 WebRequest 实例的哈希值。Returns a hash value for a WebRequest instance.

GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(继承自 MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext)

使用序列化目标对象时所需的数据填充 SerializationInfoPopulates a SerializationInfo with the data required to serialize the target object.

GetRequestStream()

获取用于写入请求数据的 Stream 对象。Gets a Stream object to use to write request data.

GetRequestStream(TransportContext)

获取用于写入请求数据的 Stream 对象,并输出与该流关联的 TransportContextGets a Stream object to use to write request data and outputs the TransportContext associated with the stream.

GetRequestStreamAsync()

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

(继承自 WebRequest)
GetResponse()

返回来自 Internet 资源的响应。Returns a response from an Internet resource.

GetResponseAsync()

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

(继承自 WebRequest)
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)
ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

显式界面实现

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

使用将目标对象序列化所需的数据填充 SerializationInfoPopulates a SerializationInfo with the data needed to serialize the target object.

安全性

WebPermission
访问请求的 URI 或请求重定向到的任何 URI。to access the requested URI or any URI that the request is redirected to. 关联的枚举: ConnectAssociated enumeration: Connect

适用于

另请参阅