.NET Framework Class Library HttpWebRequest Class Provides an HTTP-specific implementation of the WebRequest class.

Inheritance Hierarchy
Namespace:
System.Net
Assembly:
System (in System.dll)

Syntax
<SerializableAttribute> _
Public Class HttpWebRequest _
Inherits WebRequest _
Implements ISerializable
[SerializableAttribute]
public class HttpWebRequest : WebRequest,
ISerializable
[SerializableAttribute]
public ref class HttpWebRequest : public WebRequest,
ISerializable
[<SerializableAttribute>]
type HttpWebRequest =
class
inherit WebRequest
interface ISerializable
end
The HttpWebRequest type exposes the following members.

Constructors

Properties

Methods
|
| Name | Description |
|---|
.gif) .gif) | Abort | Cancels a request to an Internet resource. (Overrides WebRequest..::.Abort()()().) | .gif) | AddRange(Int32) | Adds a byte range header to a request for a specific range from the beginning or end of the requested data. | .gif) | AddRange(Int64) | Adds a byte range header to a request for a specific range from the beginning or end of the requested data. | .gif) | AddRange(Int32, Int32) | Adds a byte range header to the request for a specified range. | .gif) | AddRange(Int64, Int64) | Adds a byte range header to the request for a specified range. | .gif) | AddRange(String, Int32) | Adds a Range header to a request for a specific range from the beginning or end of the requested data. | .gif) | AddRange(String, Int64) | Adds a Range header to a request for a specific range from the beginning or end of the requested data. | .gif) | AddRange(String, Int32, Int32) | Adds a range header to a request for a specified range. | .gif) | AddRange(String, Int64, Int64) | Adds a range header to a request for a specified range. | .gif) .gif) | BeginGetRequestStream | Begins an asynchronous request for a Stream object to use to write data. (Overrides WebRequest..::.BeginGetRequestStream(AsyncCallback, Object).) | .gif) .gif) | BeginGetResponse | Begins an asynchronous request to an Internet resource. (Overrides WebRequest..::.BeginGetResponse(AsyncCallback, Object).) | .gif) | CreateObjRef | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.) | .gif) .gif) | EndGetRequestStream(IAsyncResult) | Ends an asynchronous request for a Stream object to use to write data. (Overrides WebRequest..::.EndGetRequestStream(IAsyncResult).) | .gif) | EndGetRequestStream(IAsyncResult, TransportContext%) | Ends an asynchronous request for a Stream object to use to write data and outputs the TransportContext associated with the stream. | .gif) .gif) | EndGetResponse | Ends an asynchronous request to an Internet resource. (Overrides WebRequest..::.EndGetResponse(IAsyncResult).) | .gif) .gif) | Equals(Object) | Determines whether the specified Object is equal to the current Object. (Inherited from Object.) | .gif) .gif) | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) | .gif) .gif) | GetHashCode | Serves as a hash function for a particular type. (Inherited from Object.) | .gif) | GetLifetimeService | Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) | .gif) | GetObjectData | Infrastructure. Populates a SerializationInfo with the data required to serialize the target object. (Overrides WebRequest..::.GetObjectData(SerializationInfo, StreamingContext).) | .gif) | GetRequestStream()()() | Gets a Stream object to use to write request data. (Overrides WebRequest..::.GetRequestStream()()().) | .gif) | GetRequestStream(TransportContext%) | Gets a Stream object to use to write request data and outputs the TransportContext associated with the stream. | .gif) | GetResponse | Returns a response from an Internet resource. (Overrides WebRequest..::.GetResponse()()().) | .gif) .gif) | GetType | Gets the Type of the current instance. (Inherited from Object.) | .gif) | InitializeLifetimeService | Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.) | .gif) .gif) | MemberwiseClone()()() | Creates a shallow copy of the current Object. (Inherited from Object.) | .gif) | MemberwiseClone(Boolean) | Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.) | .gif) .gif) | ToString | Returns a string that represents the current object. (Inherited from Object.) | Top

Explicit Interface Implementations

Remarks
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. Note |
|---|
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. Note |
|---|
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. |
Note |
|---|
For security reasons, cookies are disabled by default. If you want to use cookies, use the CookieContainer property to enable cookies. |
Performance IssuesA number of elements can have an impact on performance when using the HttpWebRequest class. These include the following: The ServicePointManager class. The DefaultConnectionLimit property. 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: If the application uses a proxy. If the application primarily sends data and connects to a small number of servers. If the application connects to systems that have high latency.
An application should decrease the value for the DefaultConnectionLimit property under the following conditions: 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;

Examples
The following code example creates an HttpWebRequest for the URI http://www.contoso.com/.
Dim myReq As HttpWebRequest = _
WebRequest.Create("http://www.contoso.com/")
HttpWebRequest myReq =
(HttpWebRequest)WebRequest.Create("http://www.contoso.com/");
HttpWebRequest^ myReq = dynamic_cast<HttpWebRequest^>(WebRequest::Create( "http://www.contoso.com/" ));

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileSupported in: 4, 3.5 SP1 Portable Class LibrarySupported in: Portable Class Library

.NET Framework Security

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

Thread Safety
Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also
|
Biblioteca de clases de .NET Framework HttpWebRequest (Clase) Proporciona una implementación específica de HTTP de la clase WebRequest.

Jerarquía de herencia
Espacio de nombres:
System.Net
Ensamblado:
System (en System.dll)

Sintaxis
<SerializableAttribute> _
Public Class HttpWebRequest _
Inherits WebRequest _
Implements ISerializable
[SerializableAttribute]
public class HttpWebRequest : WebRequest,
ISerializable
[SerializableAttribute]
public ref class HttpWebRequest : public WebRequest,
ISerializable
[<SerializableAttribute>]
type HttpWebRequest =
class
inherit WebRequest
interface ISerializable
end
El tipo HttpWebRequest expone los siguientes miembros.

Constructores

Propiedades

Métodos
|
| Nombre | Descripción |
|---|
.gif) .gif) | Abort | Cancela una solicitud de un recurso de Internet. (Invalida a WebRequest..::.Abort()()()). | .gif) | AddRange(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. | .gif) | AddRange(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. | .gif) | AddRange(Int32, Int32) | Agrega un encabezado de intervalo de bytes a la solicitud de un intervalo especificado. | .gif) | AddRange(Int64, Int64) | Agrega un encabezado de intervalo de bytes a la solicitud de un intervalo especificado. | .gif) | AddRange(String, Int32) | Agrega un encabezado Range a una solicitud de un intervalo específico del principio o del final de los datos solicitados. | .gif) | AddRange(String, Int64) | Agrega un encabezado Range a una solicitud de un intervalo específico del principio o del final de los datos solicitados. | .gif) | AddRange(String, Int32, Int32) | Agrega un encabezado de intervalo a una solicitud de un intervalo especificado. | .gif) | AddRange(String, Int64, Int64) | Agrega un encabezado de intervalo a una solicitud de un intervalo especificado. | .gif) .gif) | BeginGetRequestStream | Inicia una solicitud asincrónica de un objeto Stream que se va a utilizar para escribir datos. (Invalida a WebRequest..::.BeginGetRequestStream(AsyncCallback, Object)). | .gif) .gif) | BeginGetResponse | Comienza una solicitud asincrónica de un recurso de Internet. (Invalida a WebRequest..::.BeginGetResponse(AsyncCallback, Object)). | .gif) | CreateObjRef | Crea 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). | .gif) .gif) | EndGetRequestStream(IAsyncResult) | Finaliza una solicitud asincrónica para utilizar un objeto Stream para escribir datos. (Invalida a WebRequest..::.EndGetRequestStream(IAsyncResult)). | .gif) | EndGetRequestStream(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. | .gif) .gif) | EndGetResponse | Termina una solicitud asincrónica de un recurso de Internet. (Invalida a WebRequest..::.EndGetResponse(IAsyncResult)). | .gif) .gif) | Equals(Object) | Determina si el objeto Object especificado es igual al objeto Object actual. (Se hereda de Object). | .gif) .gif) | Finalize | Permite 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). | .gif) .gif) | GetHashCode | Actúa como función hash para un tipo concreto. (Se hereda de Object). | .gif) | GetLifetimeService | Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia. (Se hereda de MarshalByRefObject). | .gif) | GetObjectData | Infraestructura. Rellena SerializationInfo con los datos necesarios para serializar el objeto de destino. (Invalida a WebRequest..::.GetObjectData(SerializationInfo, StreamingContext)). | .gif) | GetRequestStream()()() | Obtiene un objeto Stream que se utilizará para escribir los datos de la solicitud. (Invalida a WebRequest..::.GetRequestStream()()()). | .gif) | GetRequestStream(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. | .gif) | GetResponse | Devuelve una respuesta desde un recurso de Internet. (Invalida a WebRequest..::.GetResponse()()()). | .gif) .gif) | GetType | Obtiene el objeto Type de la instancia actual. (Se hereda de Object). | .gif) | InitializeLifetimeService | Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia. (Se hereda de MarshalByRefObject). | .gif) .gif) | MemberwiseClone()()() | Crea una copia superficial del objeto Object actual. (Se hereda de Object). | .gif) | MemberwiseClone(Boolean) | Crea una copia superficial del objeto MarshalByRefObject actual. (Se hereda de MarshalByRefObject). | .gif) .gif) | ToString | Devuelve una cadena que representa el objeto actual. (Se hereda de Object). | Arriba

Implementaciones explícitas de interfaces

Comentarios
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. Nota |
|---|
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. Nota |
|---|
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. |
Nota |
|---|
Por razones de seguridad, de manera predeterminada las cookies están deshabilitadas. Si desea utilizar cookies, habilítelas mediante la propiedad CookieContainer. |
Problemas de rendimientoVarios elementos pueden tener un impacto en el rendimiento al usar la clase HttpWebRequest. Se incluyen las siguientes: Clase ServicePointManager Propiedad DefaultConnectionLimit 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: Si la aplicación utiliza un proxy. Si la aplicación envía principalmente datos y se conecta a un número pequeño de servidores. 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: 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;

Ejemplos
En el ejemplo de código siguiente se crea un objeto HttpWebRequest para el identificador URI http://www.contoso.com/.
Dim myReq As HttpWebRequest = _
WebRequest.Create("http://www.contoso.com/")
HttpWebRequest myReq =
(HttpWebRequest)WebRequest.Create("http://www.contoso.com/");
HttpWebRequest^ myReq = dynamic_cast<HttpWebRequest^>(WebRequest::Create( "http://www.contoso.com/" ));

Información de versión
.NET FrameworkCompatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileCompatible con: 4, 3.5 SP1 Compatible con:

Seguridad de .NET Framework

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

Seguridad para subprocesos
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.

Vea también
|