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 che contiene la risposta dalla risorsa Internet.

Eccezioni

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

-o-

TransferEncoding è impostato su un valore e SendChunked è false.

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

-o-

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

-o-

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

-o-

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

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

Abort() è stato chiamato in precedenza.

-o-

Periodo di timeout per la richiesta scaduta.

-o-

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

Cautela

WebRequest, HttpWebRequest, ServicePointe WebClient sono obsoleti e non è consigliabile usarli per nuovi sviluppi. Usare invece HttpClient.

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

Un ProtocolViolationException viene generato in diversi casi quando le proprietà impostate nella classe HttpWebRequest sono in conflitto. Questa eccezione si verifica se un'applicazione imposta la proprietà ContentLength e la proprietà SendChunked 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 proprietà ContentLength o il SendChunked viene false quando il buffering è disabilitato e in una connessione keepalive (la proprietà KeepAlive è true).

Cautela

È necessario chiamare il metodo Close 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 richieste, 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 a tempo indeterminato.

Nota

Più chiamate a GetResponse restituiscono lo stesso oggetto risposta; la richiesta non viene riemissione.

Nota

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

Nota

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

Nota

Questo membro restituisce informazioni di traccia quando si abilita la traccia di rete nell'applicazione. 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 proprietà CookieContainer per abilitare i cookie.

Si applica a

Vedi anche