HttpWebRequest.GetResponse HttpWebRequest.GetResponse HttpWebRequest.GetResponse HttpWebRequest.GetResponse Method

Definición

Devuelve una respuesta desde un recurso de Internet.Returns a response from an Internet resource.

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

Un objeto WebResponse que contiene la respuesta del recurso de Internet.A WebResponse that contains the response from the Internet resource.

Excepciones

Una llamada anterior a BeginGetResponse(AsyncCallback, Object) ya está utilizando la secuencia.The stream is already in use by a previous call to BeginGetResponse(AsyncCallback, Object).

O bien-or- TransferEncoding se establece en un valor y SendChunked es false.TransferEncoding is set to a value and SendChunked is false.

Method es GET o HEAD, y ContentLength es mayor o igual que cero o SendChunked es true.Method is GET or HEAD, and either ContentLength is greater or equal to zero or SendChunked is true.

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

O bien-or- La HttpWebRequest tiene un cuerpo de entidad, pero el método GetResponse() se invoca sin llamar al método GetRequestStream().The HttpWebRequest has an entity body but the GetResponse() method is called without calling the GetRequestStream() method.

O bien-or- ContentLength es mayor que cero, pero la aplicación no escribe todos los datos prometidos.The ContentLength is greater than zero, but the application does not write all of the promised data.

El validador de caché de la solicitud indicó que la respuesta a esta solicitud se puede obtener de la caché; sin embargo, esta solicitud incluye los datos que se deben enviar al servidor.The request cache validator indicated that the response for this request can be served from the cache; however, this request includes data to be sent to the server. Las solicitudes que envían datos no deben utilizar la caché.Requests that send data must not use the cache. Esta excepción puede producirse si usa un validador de caché personalizado que se implementa incorrectamente.This exception can occur if you are using a custom cache validator that is incorrectly implemented.

Se llamó a Abort() anteriormente.Abort() was previously called.

O bien-or- El período de tiempo de espera para la solicitud expiró.The time-out period for the request expired.

O bien-or- Error al procesar la solicitud.An error occurred while processing the request.

Ejemplos

En el ejemplo de código siguiente se obtiene la respuesta para una solicitud.The following code example gets the response for a request.

#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.The GetResponse method returns a WebResponse object that contains the response from the Internet resource. La instancia real devuelta es HttpWebResponseun y se puede convertir en una clase para obtener acceso a propiedades específicas de http.The actual instance returned is an HttpWebResponse, and can be typecast to that class to access HTTP-specific properties.

Se ProtocolViolationException produce una excepción en varios casos en los que las propiedades HttpWebRequest establecidas en la clase están en conflicto.A ProtocolViolationException is thrown in several cases when the properties set on the HttpWebRequest class are conflicting. Esta excepción se produce si una aplicación establece ContentLength la propiedad y SendChunked la propiedad trueen y, a continuación, envía una solicitud HTTP GET.This exception occurs if an application sets the ContentLength property and the SendChunked property to true, and then sends an HTTP GET request. Esta excepción se produce si una aplicación intenta enviar fragmentos a un servidor que solo admite el protocolo HTTP 1,0, donde no se admite.This exception occurs if an application tries to send chunked to a server that only supports HTTP 1.0 protocol, where this is not supported. Esta excepción se produce si una aplicación intenta enviar datos sin establecer la ContentLength propiedad SendChunked o false si está deshabilitado el almacenamiento en búfer y en una conexión keepalive KeepAlive (la truepropiedad es).This exception occurs if an application tries to send data without setting the ContentLength property or the SendChunked is false when buffering is disabled and on a keepalive connection (the KeepAlive property is true).

Precaución

Debe llamar Close al método para cerrar la secuencia y liberar la conexión.You must call the Close method to close the stream and release the connection. Si no lo hace, la aplicación puede quedarse sin conexiones.Failure to do so may cause your application to run out of connections.

Al utilizar el método POST, debe obtener la secuencia de la solicitud, escribir los datos que se van a publicar y cerrar la secuencia.When using the POST method, you must get the request stream, write the data to be posted, and close the stream. Este método se bloquea en espera de que se publique el contenido; Si no hay ningún tiempo de espera establecido y no se proporciona contenido, el subproceso que realiza la llamada se bloquea indefinidamente.This method blocks waiting for content to post; if there is no time-out set and you do not provide content, the calling thread blocks indefinitely.

Nota

Varias llamadas para GetResponse devolver el mismo objeto de respuesta; no se vuelve a emitir la solicitud.Multiple calls to GetResponse return the same response object; the request is not reissued.

Nota

La aplicación no puede mezclar métodos sincrónicos y asincrónicos para una solicitud determinada.Your application cannot mix synchronous and asynchronous methods for a particular request. Si llama al GetRequestStream método, debe utilizar el GetResponse método para recuperar la respuesta.If you call the GetRequestStream method, you must use the GetResponse method to retrieve the response.

Nota

Si se WebException produce una, utilice las Response propiedades Status y de la excepción para determinar la respuesta del servidor.If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.

Nota

Este miembro genera información de seguimiento cuando se habilita el seguimiento de red en la aplicación.This member outputs trace information when you enable network tracing in your application. Para obtener más información, consulte seguimiento de red en el .NET Framework.For more information, see Network Tracing in the .NET Framework.

Nota

Por motivos de seguridad, las cookies están deshabilitadas de forma predeterminada.For security reasons, cookies are disabled by default. Si desea usar cookies, utilice la propiedad CookieContainer para habilitar las cookies.If you wish to use cookies, use the CookieContainer property to enable cookies.

Se aplica a

Consulte también: