HttpWebRequest.GetResponse Metodo
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
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à 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è , AllowWriteStreamBuffering è falsetrue, ContentLength è -1, SendChunked è falsee Method è POST o PUT.
-o-
ha HttpWebRequest un corpo dell'entità, ma il GetResponse() metodo viene chiamato senza chiamare il GetRequestStream() metodo .
-o-
ContentLength è maggiore di zero, ma l'applicazione non scrive tutti i dati promesso.
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;
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
ServicePoint, HttpWebRequest, e WebClient sono obsoleti e non è consigliabile usarli per il nuovo sviluppo. Utilizzare invece HttpClient.
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 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 SendChunked è false quando il buffering è disabilitato e in una connessione keepalive (la KeepAlive proprietà è true).
Cautela
È 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 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 per GetResponse restituire 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 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 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 CookieContainer proprietà per abilitare i cookie.