Condividi tramite


HttpWebRequest.GetResponse Metodo

Definizione

Restituisce una risposta da una risorsa 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

Restituisce

Oggetto WebResponse contenente la risposta dalla risorsa Internet.

Eccezioni

Il flusso è già usato da una chiamata precedente a BeginGetResponse(AsyncCallback, Object).

-oppure-

TransferEncoding è impostato su un valore e SendChunked è false.

Method è GET o HEAD e ContentLength è maggiore o uguale a zero oppure SendChunked è true.

-oppure-

KeepAlive è true, AllowWriteStreamBuffering è false, ContentLength è -1, SendChunked è false e Method è POST o PUT.

-oppure-

L'oggetto HttpWebRequest ha un corpo entità, ma il metodo GetResponse() viene chiamato senza chiamare il metodo GetRequestStream().

-oppure-

L'oggetto ContentLength è maggiore di zero, ma l'applicazione non scrive tutti i dati promessi.

Il validator della cache della richiesta ha indicato che la risposta per questa richiesta può essere soddisfatta dalla cache, tuttavia la richiesta include i dati da inviare al server. Le richieste che inviano i dati non devono usare la cache. Questa eccezione può verificarsi se si usa un validator della cache personalizzato che è implementato in modo non corretto.

Abort() è stato chiamato in precedenza.

-oppure-

Il periodo di timeout per la richiesta è scaduto.

-oppure-

Si è verificato un errore durante l'elaborazione della richiesta.

Esempio

L'esempio di codice seguente ottiene la risposta per una richiesta.

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

Commenti

Il GetResponse metodo restituisce un WebResponse oggetto che contiene la risposta dalla risorsa Internet. L'istanza effettiva restituita è un HttpWebResponseoggetto e può essere typecast a tale classe per accedere alle proprietà specifiche di HTTP.

Un ProtocolViolationException oggetto viene generato in diversi casi quando le proprietà impostate nella HttpWebRequest classe sono in conflitto. Questa eccezione si verifica se un'applicazione imposta la ContentLength proprietà e la SendChunked proprietà su truee quindi invia una richiesta HTTP GET. Questa eccezione si verifica se un'applicazione tenta di inviare blocchi a un server che supporta solo il protocollo HTTP 1.0, in cui non è supportato. Questa eccezione si verifica se un'applicazione tenta di inviare dati senza impostare la ContentLength proprietà o quando falseSendChunked il buffering è disabilitato e in una connessione keepalive (la KeepAlive proprietà è true).

Attenzione

È necessario chiamare il Close metodo per chiudere il flusso e rilasciare la connessione. In caso contrario, è possibile che l'applicazione esaurisca le connessioni.

Quando si usa il metodo POST, è necessario ottenere il flusso di richiesta, scrivere i dati da pubblicare e chiudere il flusso. Questo metodo blocca l'attesa del contenuto da pubblicare; se non è stato impostato alcun timeout e non si fornisce contenuto, il thread chiamante si blocca per un periodo illimitato.

Nota

Più chiamate per GetResponse restituire lo stesso oggetto risposta. La richiesta non viene ristampata.

Nota

L'applicazione non può combinare metodi sincroni e asincroni per una determinata richiesta. Se si chiama il GetRequestStream metodo , è necessario usare il GetResponse metodo per recuperare la risposta.

Nota

Se viene generata un'eccezione WebException , utilizzare le Response proprietà e Status dell'eccezione per determinare la risposta dal server.

Nota

Questo membro genera informazioni di traccia quando viene abilitata la funzionalità di traccia di rete nell'applicazione in uso. Per altre informazioni, vedere Traccia di rete in .NET Framework.

Nota

Per motivi di sicurezza, i cookie sono disabilitati per impostazione predefinita. Se si desidera utilizzare i cookie, utilizzare la CookieContainer proprietà per abilitare i cookie.

Si applica a

Vedi anche