HttpWebRequest.GetResponse Método

Definición

Devuelve una respuesta de un recurso de Internet.

public:
 override System::Net::WebResponse ^ GetResponse();
public override System.Net.WebResponse GetResponse ();
override this.GetResponse : unit -> System.Net.WebResponse
Public Overrides Function GetResponse () As WebResponse

Devoluciones

WebResponse

WebResponse que contiene la respuesta del recurso de Internet.

Excepciones

Una llamada anterior a BeginGetResponse(AsyncCallback, Object) ya usa la secuencia.

o bien TransferEncoding se establece en un valor y SendChunked es false.

Method es GET o HEAD y ContentLength es mayor o igual a cero o SendChunked es true.

o bien KeepAlive es true, AllowWriteStreamBuffering es false, ContentLength es -1, SendChunked es false y Method es POST o PUT.

o bien La HttpWebRequest tiene un cuerpo de entidad, pero el método GetResponse() se invoca sin llamar al método GetRequestStream().

o bien ContentLength es mayor que cero, pero la aplicación no escribe todos los datos prometidos.

El validador de caché de la solicitud indicó que la respuesta para esta solicitud se puede atender desde la memoria caché; sin embargo, esta solicitud incluye datos que se deben enviar al servidor. Las solicitudes que envían datos no deben usar la caché. Esta excepción puede producirse si usa un validador de caché personalizado que se implementa incorrectamente.

Se llamó a Abort() anteriormente.

o bien Ha caducado el período del tiempo de espera de la solicitud.

o bien Error al procesar la solicitud.

Ejemplos

En el ejemplo de código siguiente se obtiene la respuesta de una solicitud.

#using <System.dll>

using namespace System;
using namespace System::Net;
using namespace System::Text;
using namespace System::IO;

// Specify the URL to receive the request.
int main()
{
   array<String^>^args = Environment::GetCommandLineArgs();
   HttpWebRequest^ request = dynamic_cast<HttpWebRequest^>(WebRequest::Create(args[1]));

   // Set some reasonable limits on resources used by this request
   request->MaximumAutomaticRedirections = 4;
   request->MaximumResponseHeadersLength = 4;

   // Set credentials to use for this request.
   request->Credentials = CredentialCache::DefaultCredentials;
   HttpWebResponse^ response = dynamic_cast<HttpWebResponse^>(request->GetResponse());
   Console::WriteLine("Content length is {0}", response->ContentLength);
   Console::WriteLine("Content type is {0}", response->ContentType);

   // Get the stream associated with the response.
   Stream^ receiveStream = response->GetResponseStream();

   // Pipes the stream to a higher level stream reader with the required encoding format.
   StreamReader^ readStream = gcnew StreamReader(receiveStream, Encoding::UTF8);
   Console::WriteLine("Response stream received.");
   Console::WriteLine(readStream->ReadToEnd());
   response->Close();
   readStream->Close();
}

/*
The output from this example will vary depending on the value passed into Main
but will be similar to the following:

Content length is 1542
Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/
using System;
using System.Net;
using System.Text;
using System.IO;

    public class Test
    {
        // Specify the URL to receive the request.
        public static void Main (string[] args)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Console.WriteLine("Content length is {0}", response.ContentLength);
            Console.WriteLine("Content type is {0}", response.ContentType);

            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream();

            // Pipes the stream to a higher level stream reader with the required encoding format.
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

            Console.WriteLine("Response stream received.");
            Console.WriteLine(readStream.ReadToEnd());
            response.Close();
            readStream.Close();
        }
    }

/*
The output from this example will vary depending on the value passed into Main
but will be similar to the following:

Content length is 1542
Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/
Imports System.Net
Imports System.Text
Imports System.IO


    Public Class Test

        ' Specify the URL to receive the request.
        Public Shared Sub Main(ByVal args() As String)
        Dim request As HttpWebRequest = CType(WebRequest.Create(args(0)), HttpWebRequest)


        ' Set some reasonable limits on resources used by this request
        request.MaximumAutomaticRedirections = 4
        request.MaximumResponseHeadersLength = 4

        ' Set credentials to use for this request.
        request.Credentials = CredentialCache.DefaultCredentials

        Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)

        Console.WriteLine("Content length is {0}", response.ContentLength)
        Console.WriteLine("Content type is {0}", response.ContentType)

        ' Get the stream associated with the response.
        Dim receiveStream As Stream = response.GetResponseStream()

        ' Pipes the stream to a higher level stream reader with the required encoding format. 
        Dim readStream As New StreamReader(receiveStream, Encoding.UTF8)

        Console.WriteLine("Response stream received.")
        Console.WriteLine(readStream.ReadToEnd())
        response.Close()
        readStream.Close()
    End Sub
End Class
'
'The output from this example will vary depending on the value passed into Main 
'but will be similar to the following:
'
'Content length is 1542
'Content type is text/html; charset=utf-8
'Response stream received.
'...
'
'

Comentarios

El GetResponse método devuelve un WebResponse objeto que contiene la respuesta del recurso de Internet. La instancia real devuelta es , HttpWebResponsey se puede escribir en esa clase para tener acceso a propiedades específicas de HTTP.

ProtocolViolationException Se produce una excepción en varios casos cuando las propiedades establecidas en la HttpWebRequest clase están en conflicto. Esta excepción se produce si una aplicación establece la ContentLength propiedad y la SendChunked propiedad trueen y, a continuación, envía una solicitud HTTP GET. Esta excepción se produce si una aplicación intenta enviar fragmentado a un servidor que solo admite el protocolo HTTP 1.0, donde no se admite. Esta excepción se produce si una aplicación intenta enviar datos sin establecer la ContentLength propiedad o SendChunked es false cuando el almacenamiento en búfer está deshabilitado y en una conexión keepalive (la KeepAlive propiedad es true).

Precaución

Debe llamar al Close método para cerrar la secuencia y liberar la conexión. Si no lo hace, es posible que la aplicación se quede sin conexiones.

Al usar el método POST, debe obtener el flujo de solicitud, escribir los datos que se van a publicar y cerrar la secuencia. Este método bloquea la espera de que el contenido se publique; Si no hay ningún tiempo de espera establecido y no proporciona contenido, el subproceso que realiza la llamada se bloquea indefinidamente.

Nota

Varias llamadas para devolver el mismo objeto de respuesta; la solicitud no se vuelve a GetResponse emitir.

Nota

La aplicación no puede mezclar métodos sincrónicos y asincrónicos para una solicitud determinada. Si llama al GetRequestStream método , debe usar el GetResponse método para recuperar la respuesta.

Nota

Si se produce una WebException excepción , use las Response propiedades y Status de la excepción para determinar la respuesta del servidor.

Nota

Este miembro genera información de seguimiento cuando se habilita el seguimiento de red en la aplicación. Para obtener más información, vea Seguimiento de red en .NET Framework.

Nota

Por motivos de seguridad, las cookies están deshabilitadas de forma predeterminada. Si desea utilizar cookies, utilice la CookieContainer propiedad para habilitar las cookies.

Se aplica a

Consulte también