Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
.NET Framework Class Library
HttpWebRequest Class

Provides an HTTP-specific implementation of the WebRequest class.

System..::.Object
  System..::.MarshalByRefObject
    System.Net..::.WebRequest
      System.Net..::.HttpWebRequest

Namespace:  System.Net
Assembly:  System (in System.dll)
Visual Basic
<SerializableAttribute> _
Public Class HttpWebRequest _
    Inherits WebRequest _
    Implements ISerializable
C#
[SerializableAttribute]
public class HttpWebRequest : WebRequest, 
    ISerializable
Visual C++
[SerializableAttribute]
public ref class HttpWebRequest : public WebRequest, 
    ISerializable
F#
[<SerializableAttribute>]
type HttpWebRequest =  
    class
        inherit WebRequest
        interface ISerializable
    end

The HttpWebRequest type exposes the following members.

  NameDescription
Protected methodHttpWebRequest Obsolete. Initializes a new instance of the HttpWebRequest class from the specified instances of the SerializationInfo and StreamingContext classes.
Top
  NameDescription
Public propertySupported by Portable Class LibraryAcceptGets or sets the value of the Accept HTTP header.
Public propertyAddressGets the Uniform Resource Identifier (URI) of the Internet resource that actually responds to the request.
Public propertyAllowAutoRedirectGets or sets a value that indicates whether the request should follow redirection responses.
Public propertyAllowWriteStreamBufferingGets or sets a value that indicates whether to buffer the data sent to the Internet resource.
Public propertyAuthenticationLevelGets or sets values indicating the level of authentication and impersonation used for this request. (Inherited from WebRequest.)
Public propertyAutomaticDecompressionGets or sets the type of decompression that is used.
Public propertyCachePolicyGets or sets the cache policy for this request. (Inherited from WebRequest.)
Public propertyClientCertificatesGets or sets the collection of security certificates that are associated with this request.
Public propertyConnectionGets or sets the value of the Connection HTTP header.
Public propertyConnectionGroupNameGets or sets the name of the connection group for the request. (Overrides WebRequest..::.ConnectionGroupName.)
Public propertyContentLengthGets or sets the Content-length HTTP header. (Overrides WebRequest..::.ContentLength.)
Public propertySupported by Portable Class LibraryContentTypeGets or sets the value of the Content-type HTTP header. (Overrides WebRequest..::.ContentType.)
Public propertyContinueDelegateGets or sets the delegate method called when an HTTP 100-continue response is received from the Internet resource.
Public propertySupported by Portable Class LibraryCookieContainerGets or sets the cookies associated with the request.
Public propertyCredentialsGets or sets authentication information for the request. (Overrides WebRequest..::.Credentials.)
Public propertyDateGet or set the Date HTTP header value to use in an HTTP request.
Public propertyStatic memberDefaultCachePolicyGets or sets the default cache policy for this request.
Public propertyStatic memberDefaultMaximumErrorResponseLengthGets or sets the default maximum length of an HTTP error response.
Public propertyStatic memberDefaultMaximumResponseHeadersLengthGets or sets the default for the MaximumResponseHeadersLength property.
Public propertyExpectGets or sets the value of the Expect HTTP header.
Public propertySupported by Portable Class LibraryHaveResponseGets a value that indicates whether a response has been received from an Internet resource.
Public propertySupported by Portable Class LibraryHeadersSpecifies a collection of the name/value pairs that make up the HTTP headers. (Overrides WebRequest..::.Headers.)
Public propertyHostGet or set the Host header value to use in an HTTP request independent from the request URI.
Public propertyIfModifiedSinceGets or sets the value of the If-Modified-Since HTTP header.
Public propertyImpersonationLevelGets or sets the impersonation level for the current request. (Inherited from WebRequest.)
Public propertyKeepAliveGets or sets a value that indicates whether to make a persistent connection to the Internet resource.
Public propertyMaximumAutomaticRedirectionsGets or sets the maximum number of redirects that the request follows.
Public propertyMaximumResponseHeadersLengthGets or sets the maximum allowed length of the response headers.
Public propertyMediaTypeGets or sets the media type of the request.
Public propertySupported by Portable Class LibraryMethodGets or sets the method for the request. (Overrides WebRequest..::.Method.)
Public propertyPipelinedGets or sets a value that indicates whether to pipeline the request to the Internet resource.
Public propertyPreAuthenticateGets or sets a value that indicates whether to send an Authorization header with the request. (Overrides WebRequest..::.PreAuthenticate.)
Public propertyProtocolVersionGets or sets the version of HTTP to use for the request.
Public propertyProxyGets or sets proxy information for the request. (Overrides WebRequest..::.Proxy.)
Public propertyReadWriteTimeoutGets or sets a time-out in milliseconds when writing to or reading from a stream.
Public propertyRefererGets or sets the value of the Referer HTTP header.
Public propertySupported by Portable Class LibraryRequestUriGets the original Uniform Resource Identifier (URI) of the request. (Overrides WebRequest..::.RequestUri.)
Public propertySendChunkedGets or sets a value that indicates whether to send data in segments to the Internet resource.
Public propertyServicePointGets the service point to use for the request.
Public propertySupported by Portable Class LibrarySupportsCookieContainer
Public propertyTimeoutGets or sets the time-out value in milliseconds for the GetResponse and GetRequestStream methods. (Overrides WebRequest..::.Timeout.)
Public propertyTransferEncodingGets or sets the value of the Transfer-encoding HTTP header.
Public propertyUnsafeAuthenticatedConnectionSharingGets or sets a value that indicates whether to allow high-speed NTLM-authenticated connection sharing.
Public propertyUseDefaultCredentialsGets or sets a Boolean value that controls whether default credentials are sent with requests. (Overrides WebRequest..::.UseDefaultCredentials.)
Public propertyUserAgentGets or sets the value of the User-agent HTTP header.
Top
  NameDescription
Public methodSupported by Portable Class LibraryAbortCancels a request to an Internet resource. (Overrides WebRequest..::.Abort()()().)
Public methodAddRange(Int32)Adds a byte range header to a request for a specific range from the beginning or end of the requested data.
Public methodAddRange(Int64)Adds a byte range header to a request for a specific range from the beginning or end of the requested data.
Public methodAddRange(Int32, Int32)Adds a byte range header to the request for a specified range.
Public methodAddRange(Int64, Int64)Adds a byte range header to the request for a specified range.
Public methodAddRange(String, Int32)Adds a Range header to a request for a specific range from the beginning or end of the requested data.
Public methodAddRange(String, Int64)Adds a Range header to a request for a specific range from the beginning or end of the requested data.
Public methodAddRange(String, Int32, Int32)Adds a range header to a request for a specified range.
Public methodAddRange(String, Int64, Int64)Adds a range header to a request for a specified range.
Public methodSupported by Portable Class LibraryBeginGetRequestStreamBegins an asynchronous request for a Stream object to use to write data. (Overrides WebRequest..::.BeginGetRequestStream(AsyncCallback, Object).)
Public methodSupported by Portable Class LibraryBeginGetResponseBegins an asynchronous request to an Internet resource. (Overrides WebRequest..::.BeginGetResponse(AsyncCallback, Object).)
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodSupported by Portable Class LibraryEndGetRequestStream(IAsyncResult)Ends an asynchronous request for a Stream object to use to write data. (Overrides WebRequest..::.EndGetRequestStream(IAsyncResult).)
Public methodEndGetRequestStream(IAsyncResult, TransportContext%)Ends an asynchronous request for a Stream object to use to write data and outputs the TransportContext associated with the stream.
Public methodSupported by Portable Class LibraryEndGetResponseEnds an asynchronous request to an Internet resource. (Overrides WebRequest..::.EndGetResponse(IAsyncResult).)
Public methodSupported by Portable Class LibraryEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by Portable Class LibraryFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Portable Class LibraryGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodGetObjectDataInfrastructure. Populates a SerializationInfo with the data required to serialize the target object. (Overrides WebRequest..::.GetObjectData(SerializationInfo, StreamingContext).)
Public methodGetRequestStream()()()Gets a Stream object to use to write request data. (Overrides WebRequest..::.GetRequestStream()()().)
Public methodGetRequestStream(TransportContext%)Gets a Stream object to use to write request data and outputs the TransportContext associated with the stream.
Public methodGetResponseReturns a response from an Internet resource. (Overrides WebRequest..::.GetResponse()()().)
Public methodSupported by Portable Class LibraryGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodSupported by Portable Class LibraryMemberwiseClone()()()Creates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public methodSupported by Portable Class LibraryToStringReturns a string that represents the current object. (Inherited from Object.)
Top
  NameDescription
Explicit interface implemetationPrivate methodISerializable..::.GetObjectDataInfrastructure. Populates a SerializationInfo with the data needed to serialize the target object.
Top

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.

Do not use the HttpWebRequest constructor. Use the WebRequest..::.Create method to initialize new HttpWebRequest objects. If the scheme for the Uniform Resource Identifier (URI) is http:// or https://, Create returns an HttpWebRequest object.

The GetResponse method makes a synchronous request to the resource specified in the RequestUri property and returns an HttpWebResponse that contains the response. You can make an asynchronous request to the resource using the BeginGetResponse and EndGetResponse methods.

When you want to send data to the resource, the GetRequestStream method returns a Stream object to use to send data. The BeginGetRequestStream and EndGetRequestStream methods provide asynchronous access to the send data stream.

For client authentication with HttpWebRequest, the client certificate must be installed in the My certificate store of the current user.

The HttpWebRequest class throws a WebException when errors occur while accessing a resource. The WebException..::.Status property contains a WebExceptionStatus value that indicates the source of the error. When WebException..::.Status is WebExceptionStatus..::.ProtocolError, the Response property contains the HttpWebResponse received from the resource.

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

The following table lists the HTTP headers that are set either by properties or methods or the system.

Header

Set by

Accept

Set by the Accept property.

Connection

Set by the Connection property, KeepAlive property.

Content-Length

Set by the ContentLength property.

Content-Type

Set by the ContentType property.

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-Since

Set by the IfModifiedSince property.

Range

Set by the AddRange method.

Referer

Set by the Referer property.

Transfer-Encoding

Set by the TransferEncoding property (the SendChunked property must be true).

User-Agent

Set by the UserAgent property.

NoteNote

HttpWebRequest is registered automatically. 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. 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. 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. If there are no proxy settings in Internet Explorer, the request is sent directly to the server.

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. For example, the HttpWebRequest class will parse a bypass list of "nt*" from Internet Explorer as a regular expression of "nt.$". This differs from the native behavior of 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.

The HttpWebRequest class contains new members when it is used in a Portable Class Library project. For more information, see API Differences in Portable Class Library.

NoteNote

The Framework caches SSL sessions as they are created and attempts to reuse a cached session for a new request, if possible. 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.

NoteNote

For security reasons, cookies are disabled by default. If you want to use cookies, use the CookieContainer property to enable cookies.

Performance Issues

A number of elements can have an impact on performance when using the HttpWebRequest class. These include the following:

  1. The ServicePointManager class.

  2. The DefaultConnectionLimit property.

  3. The UseNagleAlgorithm property.

The ServicePointManager is an object that provides connection management for HTTP connections. The ServicePointManager is a static class that creates maintains and deletes instances of the ServicePoint class. Each ServicePoint instance handles or manages connections to Internet resources based on the host Uri. After the first connection made to a host Uri, each subsequent request will use the information provided by the ServicePoint instance.

ServicePoint mySP = ServicePointManager.FindServicePoint(myUri);

The DefaultConnectionLimit property allows an application to specify how many concurrent connections should be allowed to any given resource. An application using a HttpWebRequest instance is able to specify the maximum number of concurrent persistent connections that it will have to a server. By default this is property is set to 2. So when the ServicePointManager creates a ServicePoint instance, it will assign the ConnectionLimit property to the value of the DefaultConnectionLimit property that is set on the ServicePointManager class.

The best value for the DefaultConnectionLimit property depends on the application workload and proxy settings. A general recommendation when only connecting to a few hosts or connecting through a proxy is to use a value that is 12 times the number of CPUs on the local computer. So for a computer with 4 CPUs using a proxy, the recommended value would be 48.

ServicePointManager.DefaultConnectionLimit = 48;

An application should increase the value for the DefaultConnectionLimit property under the following conditions:

  1. If the application uses a proxy.

  2. If the application primarily sends data and connects to a small number of servers.

  3. If the application connects to systems that have high latency.

An application should decrease the value for the DefaultConnectionLimit property under the following conditions:

  1. If the application is memory or resource constrained.

Another option that can have an impact on performance is the use of the UseNagleAlgorithm property. When this property is set to true, TCP/IP will try to use the TCP Nagle algorithm for HTTP connections. The Nagle algorithm aggregates data when sending TCP packets. It accumulates sequences of small messages into larger TCP packets before the data is sent over the network. Using the Nagle algorithm can optimize the use of network resources, although in some situations performance can also be degraded. Generally for constant high-volume throughput, a performance improvement is realized using the Nagle algorithm. But for smaller throughput applications, degradation in performance may be seen.

An application doesn't normally need to change the default value for the UseNagleAlgorithm property which is set to true. However, if an application is using low-latency connections, it may help to set this property to false.

ServicePointManager.UseNagleAlgorithm = false;

The following code example creates an HttpWebRequest for the URI http://www.contoso.com/.

Visual Basic

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

C#

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

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

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library
  • WebPermission 

    to access the requested URI or any URI that the request is redirected to. Associated enumeration: Connect

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Biblioteca de clases de .NET Framework
HttpWebRequest (Clase)

Proporciona una implementación específica de HTTP de la clase WebRequest.

System..::.Object
  System..::.MarshalByRefObject
    System.Net..::.WebRequest
      System.Net..::.HttpWebRequest

Espacio de nombres:  System.Net
Ensamblado:  System (en System.dll)
Visual Basic
<SerializableAttribute> _
Public Class HttpWebRequest _
    Inherits WebRequest _
    Implements ISerializable
C#
[SerializableAttribute]
public class HttpWebRequest : WebRequest, 
    ISerializable
Visual C++
[SerializableAttribute]
public ref class HttpWebRequest : public WebRequest, 
    ISerializable
F#
[<SerializableAttribute>]
type HttpWebRequest =  
    class
        inherit WebRequest
        interface ISerializable
    end

El tipo HttpWebRequest expone los siguientes miembros.

  NombreDescripción
Método protegidoHttpWebRequest Obsoleto. Inicializa una nueva instancia de la clase HttpWebRequest a partir de las instancias especificadas de las clases SerializationInfo y StreamingContext.
Arriba
  NombreDescripción
Propiedad pública8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifAcceptObtiene o establece el valor del encabezado HTTP Accept.
Propiedad públicaAddressObtiene el identificador URI del recurso de Internet que respondió realmente a la solicitud.
Propiedad públicaAllowAutoRedirectObtiene o establece un valor que indica si la solicitud debe seguir las respuestas de redireccionamiento.
Propiedad públicaAllowWriteStreamBufferingObtiene o establece un valor que indica si se deben almacenar en el búfer los datos enviados al recurso de Internet.
Propiedad públicaAuthenticationLevelObtiene o establece valores que indican el nivel de autenticación y de suplantación utilizados para esta solicitud. (Se hereda de WebRequest).
Propiedad públicaAutomaticDecompressionObtiene o establece el tipo de descompresión que se utiliza.
Propiedad públicaCachePolicyObtiene o establece la directiva de caché para esta solicitud. (Se hereda de WebRequest).
Propiedad públicaClientCertificatesObtiene o establece la colección de certificados de seguridad asociados a esta solicitud.
Propiedad públicaConnectionObtiene o establece el valor del encabezado HTTP Connection.
Propiedad públicaConnectionGroupNameObtiene o establece el nombre del grupo de conexiones para la solicitud. (Invalida a WebRequest..::.ConnectionGroupName).
Propiedad públicaContentLengthObtiene o establece el encabezado HTTP Content-length. (Invalida a WebRequest..::.ContentLength).
Propiedad pública8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifContentTypeObtiene o establece el valor del encabezado HTTP Content-type. (Invalida a WebRequest..::.ContentType).
Propiedad públicaContinueDelegateObtiene o establece el método de delegado al que se llama cuando se recibe una respuesta HTTP 100-continue desde el recurso de Internet.
Propiedad pública8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifCookieContainerObtiene o establece las cookies asociadas a la solicitud.
Propiedad públicaCredentialsObtiene o establece la información de autenticación para la solicitud. (Invalida a WebRequest..::.Credentials).
Propiedad públicaDateObtiene o establece el valor del encabezado HTTP Date que se va a usar en una solicitud HTTP.
Propiedad públicaMiembro estáticoDefaultCachePolicyObtiene o establece la directiva de caché predeterminada para esta solicitud.
Propiedad públicaMiembro estáticoDefaultMaximumErrorResponseLengthObtiene o establece la longitud máxima predeterminada de una respuesta de error de HTTP.
Propiedad públicaMiembro estáticoDefaultMaximumResponseHeadersLengthObtiene o establece el valor predeterminado de la propiedad MaximumResponseHeadersLength.
Propiedad públicaExpectObtiene o establece el valor del encabezado HTTP Expect.
Propiedad pública8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifHaveResponseObtiene un valor que indica si se ha recibido una respuesta de un recurso de Internet.
Propiedad pública8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifHeadersEspecifica una colección de los pares nombre/valor que componen los encabezados HTTP. (Invalida a WebRequest..::.Headers).
Propiedad públicaHostObtiene o establece el valor del encabezado Host que se va a usar en una solicitud HTTP independiente del identificador URI de la solicitud.
Propiedad públicaIfModifiedSinceObtiene o establece el valor del encabezado HTTP If-Modified-Since.
Propiedad públicaImpersonationLevelObtiene o establece el nivel de suplantación para la solicitud actual. (Se hereda de WebRequest).
Propiedad públicaKeepAliveObtiene o establece un valor que indica si se debe establecer una conexión persistente en el recurso de Internet.
Propiedad públicaMaximumAutomaticRedirectionsObtiene o establece el número máximo de redirecciones que seguirá la solicitud.
Propiedad públicaMaximumResponseHeadersLengthObtiene o establece la longitud máxima permitida de los encabezados de respuesta.
Propiedad públicaMediaTypeObtiene o establece el tipo del medio de la solicitud.
Propiedad pública8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifMethodObtiene o establece el método para la solicitud. (Invalida a WebRequest..::.Method).
Propiedad públicaPipelinedObtiene o establece un valor que indica si se debe canalizar la solicitud en el recurso de Internet.
Propiedad públicaPreAuthenticateObtiene o establece un valor que indica si se envía un encabezado de autorización con la solicitud. (Invalida a WebRequest..::.PreAuthenticate).
Propiedad públicaProtocolVersionObtiene o establece la versión de HTTP que se va a utilizar para la solicitud.
Propiedad públicaProxyObtiene o establece la información de proxy para la solicitud. (Invalida a WebRequest..::.Proxy).
Propiedad públicaReadWriteTimeoutObtiene o establece un tiempo de espera, en milisegundos, al leer o escribir una secuencia.
Propiedad públicaRefererObtiene o establece el valor del encabezado HTTP Referer.
Propiedad pública8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifRequestUriObtiene el identificador URI original de la solicitud. (Invalida a WebRequest..::.RequestUri).
Propiedad públicaSendChunkedObtiene o establece un valor que indica si se deben enviar los datos segmentados al recurso de Internet.
Propiedad públicaServicePointObtiene el punto de servicio que se va a utilizar para la solicitud.
Propiedad pública8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifSupportsCookieContainer
Propiedad públicaTimeoutObtiene o establece el valor de tiempo de espera, en milisegundos, para los métodos GetResponse y GetRequestStream. (Invalida a WebRequest..::.Timeout).
Propiedad públicaTransferEncodingObtiene o establece el valor del encabezado HTTP Transfer-encoding.
Propiedad públicaUnsafeAuthenticatedConnectionSharingObtiene o establece un valor que indica si se permite el uso compartido de las conexiones de alta velocidad autenticadas por NTLM.
Propiedad públicaUseDefaultCredentialsObtiene o establece el valor Boolean que controla si se envían las credenciales predeterminadas con las solicitudes. (Invalida a WebRequest..::.UseDefaultCredentials).
Propiedad públicaUserAgentObtiene o establece el valor del encabezado HTTP User-agent.
Arriba
  NombreDescripción
Método público8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifAbortCancela una solicitud de un recurso de Internet. (Invalida a WebRequest..::.Abort()()()).
Método públicoAddRange(Int32)Agrega un encabezado de intervalo de bytes a una solicitud de un intervalo específico desde el principio o el final de los datos solicitados.
Método públicoAddRange(Int64)Agrega un encabezado de intervalo de bytes a una solicitud de un intervalo específico desde el principio o el final de los datos solicitados.
Método públicoAddRange(Int32, Int32)Agrega un encabezado de intervalo de bytes a la solicitud de un intervalo especificado.
Método públicoAddRange(Int64, Int64)Agrega un encabezado de intervalo de bytes a la solicitud de un intervalo especificado.
Método públicoAddRange(String, Int32)Agrega un encabezado Range a una solicitud de un intervalo específico del principio o del final de los datos solicitados.
Método públicoAddRange(String, Int64)Agrega un encabezado Range a una solicitud de un intervalo específico del principio o del final de los datos solicitados.
Método públicoAddRange(String, Int32, Int32)Agrega un encabezado de intervalo a una solicitud de un intervalo especificado.
Método públicoAddRange(String, Int64, Int64)Agrega un encabezado de intervalo a una solicitud de un intervalo especificado.
Método público8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifBeginGetRequestStreamInicia una solicitud asincrónica de un objeto Stream que se va a utilizar para escribir datos. (Invalida a WebRequest..::.BeginGetRequestStream(AsyncCallback, Object)).
Método público8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifBeginGetResponseComienza una solicitud asincrónica de un recurso de Internet. (Invalida a WebRequest..::.BeginGetResponse(AsyncCallback, Object)).
Método públicoCreateObjRefCrea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto. (Se hereda de MarshalByRefObject).
Método público8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifEndGetRequestStream(IAsyncResult)Finaliza una solicitud asincrónica para utilizar un objeto Stream para escribir datos. (Invalida a WebRequest..::.EndGetRequestStream(IAsyncResult)).
Método públicoEndGetRequestStream(IAsyncResult, TransportContext%)Finaliza una solicitud asincrónica de un objeto Stream que se va a usar para escribir los datos y genera el objeto TransportContext asociado a la secuencia.
Método público8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifEndGetResponseTermina una solicitud asincrónica de un recurso de Internet. (Invalida a WebRequest..::.EndGetResponse(IAsyncResult)).
Método público8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifEquals(Object)Determina si el objeto Object especificado es igual al objeto Object actual. (Se hereda de Object).
Método protegido8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifFinalizePermite que un objeto intente liberar recursos y realizar otras operaciones de limpieza antes de ser reclamado por la recolección de elementos no utilizados. (Se hereda de Object).
Método público8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifGetHashCodeActúa como función hash para un tipo concreto. (Se hereda de Object).
Método públicoGetLifetimeServiceRecupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia. (Se hereda de MarshalByRefObject).
Método protegidoGetObjectDataInfraestructura. Rellena SerializationInfo con los datos necesarios para serializar el objeto de destino. (Invalida a WebRequest..::.GetObjectData(SerializationInfo, StreamingContext)).
Método públicoGetRequestStream()()()Obtiene un objeto Stream que se utilizará para escribir los datos de la solicitud. (Invalida a WebRequest..::.GetRequestStream()()()).
Método públicoGetRequestStream(TransportContext%)Obtiene un objeto Stream que se va a usar para escribir los datos de la solicitud y genera el objeto TransportContext asociado a la secuencia.
Método públicoGetResponseDevuelve una respuesta desde un recurso de Internet. (Invalida a WebRequest..::.GetResponse()()()).
Método público8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifGetTypeObtiene el objeto Type de la instancia actual. (Se hereda de Object).
Método públicoInitializeLifetimeServiceObtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia. (Se hereda de MarshalByRefObject).
Método protegido8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifMemberwiseClone()()()Crea una copia superficial del objeto Object actual. (Se hereda de Object).
Método protegidoMemberwiseClone(Boolean)Crea una copia superficial del objeto MarshalByRefObject actual. (Se hereda de MarshalByRefObject).
Método público8y7x3zz2.PortableClassLibrary(es-es,VS.100).gifToStringDevuelve una cadena que representa el objeto actual. (Se hereda de Object).
Arriba
  NombreDescripción
Implementación explícita de interfacesMétodo privadoISerializable..::.GetObjectDataInfraestructura. Llena SerializationInfo con los datos necesarios para serializar el objeto de destino.
Arriba

La clase HttpWebRequest hace que se admitan las propiedades y los métodos definidos en WebRequest y que las propiedades y los métodos adicionales permitan al usuario interactuar directamente con servidores que utilicen HTTP.

No utilice el constructor HttpWebRequest. Utilice el método WebRequest..::.Create para inicializar nuevos objetos HttpWebRequest. Si el esquema para el identificador URI es http:// o https://, Create devuelve un objeto HttpWebRequest.

El método GetResponse realiza una solicitud sincrónica al recurso especificado en la propiedad RequestUri y devuelve un objeto HttpWebResponse con la respuesta. Para realizar una solicitud asincrónica al recurso, utilice los métodos BeginGetResponse y EndGetResponse.

Si desea enviar datos al recurso, el método GetRequestStream devuelve un objeto Stream que se utiliza para enviar datos. Los métodos BeginGetRequestStream y EndGetRequestStream proporcionan acceso asincrónico al flujo de datos de envío.

Para la autenticación del cliente con HttpWebRequest, se debe instalar el certificado del cliente en el almacén de certificados My del usuario actual.

La clase HttpWebRequest produce una excepción WebException cuando se producen errores en el acceso a un recurso. La propiedad WebException..::.Status contiene un valor WebExceptionStatus que indica el origen del error. Si WebException..::.Status es WebExceptionStatus..::.ProtocolError, la propiedad Response contiene el valor de HttpWebResponse recibido del recurso.

HttpWebRequest expone valores de encabezado HTTP comunes enviados al recurso de Internet como propiedades. Dichos valores se encuentran establecidos por métodos o por el sistema. En la tabla siguiente se presenta una lista completa. Es posible establecer otros encabezados en la propiedad Headers como pares nombre/valor. Tenga en cuenta que los servidores y cachés pueden cambiar o agregar encabezados durante la solicitud.

En la tabla siguiente se muestran los encabezados HTTP establecidos por propiedades o métodos, o por el sistema.

Encabezado

Establecido por

Accept

La propiedad Accept.

Conexión

Las propiedades Connection y KeepAlive.

Content-Length

La propiedad ContentLength.

Content-Type

La propiedad ContentType.

Expect

La propiedad Expect.

Fecha

El sistema con la fecha actual.

Host

El sistema con la información de host actual.

If-Modified-Since

La propiedad IfModifiedSince.

Intervalo

El método AddRange.

Referer

La propiedad Referer.

Transfer-Encoding

Establecido por la propiedad TransferEncoding (la propiedad SendChunked debe ser true).

User-Agent

La propiedad UserAgent.

NotaNota

HttpWebRequest se registra automáticamente. No es necesario llamar al método RegisterPrefix para registrar System.Net..::.HttpWebRequest antes de usar identificadores URI que comiencen con http:// o https://.

El archivo de configuración de la aplicación o el equipo local puede especificar que se use un proxy predeterminado. Si se especifica la propiedad Proxy, la configuración de proxy de la propiedad Proxy invalidará el archivo de configuración de la aplicación o el equipo local y la instancia de HttpWebRequest usará la configuración de proxy especificada. Si no se especifica ningún proxy en el archivo de configuración y tampoco se especifica la propiedad Proxy, la clase HttpWebRequest usará la configuración de proxy heredada de Internet Explorer en el equipo local. Si no hay ninguna configuración de proxy en Internet Explorer, la solicitud se enviará directamente al servidor.

La clase HttpWebRequest analiza una lista de omisión de proxy con caracteres comodín heredada de Internet Explorer de distinto modo en que Internet Explorer analiza directamente la lista de omisión. Por ejemplo, la clase HttpWebRequest analiza una lista de omisión "nt*" de Internet Explorer como una expresión regular "nt.$". Este comportamiento difiere del comportamiento nativo de Internet Explorer. De modo que una dirección URL "http://intxxxxx" omitiría el proxy utilizando la clase HttpWebRequest, pero no omitiría el proxy utilizando Internet Explorer.

La clase HttpWebRequest contiene los nuevos miembros cuando se utiliza en un proyecto Biblioteca de clases portable. Para obtener más información, vea Diferencias de API de la biblioteca de clases portable.

NotaNota

El marco de trabajo almacena en caché las sesiones de SSL a medida que se crean, e intenta reutilizar una sesión almacenada en memoria caché para una nueva solicitud, si es posible. Si intenta reutilizar una sesión de SSL, el Framework utiliza el primer elemento de ClientCertificates (si existe) o intenta reutilizar una sesión anónima si el valor de ClientCertificates está vacío.

NotaNota

Por razones de seguridad, de manera predeterminada las cookies están deshabilitadas. Si desea utilizar cookies, habilítelas mediante la propiedad CookieContainer.

Problemas de rendimiento

Varios elementos pueden tener un impacto en el rendimiento al usar la clase HttpWebRequest. Se incluyen las siguientes:

  1. Clase ServicePointManager

  2. Propiedad DefaultConnectionLimit

  3. Propiedad UseNagleAlgorithm

ServicePointManager es un objeto que proporciona la administración de la conexión para las conexiones HTTP. La clase estática ServicePointManager es una clase estática que crea, mantiene y elimina instancias de la clase ServicePoint. Cada identificador de instancia ServicePoint controla las conexiones a los recursos de Internet basados en el Uri del host. Después de que la primera conexión a Uri del host, cada solicitud subsiguiente utilizará la información proporcionada por la instancia ServicePoint.

ServicePoint mySP = ServicePointManager.FindServicePoint(myUri);

La propiedad DefaultConnectionLimit permite a una aplicación especificar cuántas conexiones simultáneas se deberían permitir a cualquier recurso determinado. Una aplicación que usa una instancia HttpWebRequest puede especificar el número máximo de conexiones persistentes simultáneas que tendrá con un servidor. De forma predeterminada, esta propiedad está establecida en 2. Por tanto, cuando ServicePointManager crea una instancia de ServicePoint, asignará la propiedad ConnectionLimit al valor de la propiedad DefaultConnectionLimit que se establece en la clase ServicePointManager.

El valor mejor para la propiedad DefaultConnectionLimit depende de la carga de trabajo de la aplicación y de la configuración de proxy. Una recomendación general al conectarse solamente a algunos hosts o conectarse mediante un proxy es usar un valor que sea 12 multiplicado por el número de CPU del equipo local. Por tanto, para un equipo con 4 CPU que usa un proxy, el valor recomendado será 48.

ServicePointManager.DefaultConnectionLimit = 48;

Una aplicación debería aumentar el valor de la propiedad DefaultConnectionLimit en las siguientes condiciones:

  1. Si la aplicación utiliza un proxy.

  2. Si la aplicación envía principalmente datos y se conecta a un número pequeño de servidores.

  3. Si la aplicación se conecta a los sistemas que tienen alta latencia.

Una aplicación debería disminuir el valor de la propiedad DefaultConnectionLimit en las siguientes condiciones:

  1. Si la aplicación tiene restricciones de memoria o recursos.

Otra opción que puede tener impacto en el rendimiento es el uso de la propiedad UseNagleAlgorithm. Cuando esta propiedad se establece en true, TCP/IP intentará utilizar el algoritmo de TCP Nagle para las conexiones HTTP. El algoritmo de Nagle agrega datos al enviar paquetes TCP. Acumula secuencias de mensajes pequeños en los paquetes TCP mayores antes de que los datos se envíen a través de la red. La utilización del algoritmo de Nagle puede optimizar el uso de recursos de la red, aunque en algunas situaciones también se puede degradar el rendimiento. Generalmente para el volumen de alto rendimiento constante, se consigue una mejora de rendimiento utilizando el algoritmo de Nagle. Pero para aplicaciones de rendimiento menores, la degradación del rendimiento se puede ver.

Una aplicación no necesita cambiar normalmente el valor predeterminado para la propiedad UseNagleAlgorithm que se establece en true. Sin embargo, si una aplicación está utilizando conexiones de latencia baja, puede ayudar establecer esta propiedad en false.

ServicePointManager.UseNagleAlgorithm = false;

En el ejemplo de código siguiente se crea un objeto HttpWebRequest para el identificador URI http://www.contoso.com/.

Visual Basic

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

C#

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

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

.NET Framework

Compatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1

Compatible con:
  • WebPermission 

    para obtener acceso al URI solicitado o a cualquier URI al que se haya redirigido la solicitud. Enumeración asociada: Connect

Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
Todos los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker