HttpWebRequest.GetResponse Método
Definição
Retorna uma resposta de um recurso da 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
Retornos
Um WebResponse que contém a resposta do recurso da Internet.A WebResponse that contains the response from the Internet resource.
Exceções
O fluxo já está sendo usado por uma chamada anterior para BeginGetResponse(AsyncCallback, Object).The stream is already in use by a previous call to BeginGetResponse(AsyncCallback, Object).
- ou --or-
TransferEncoding é definido como um valor e SendChunked é false.TransferEncoding is set to a value and SendChunked is false.
Method é GET ou HEAD e ContentLength é maior ou igual a zero ou SendChunked é true.Method is GET or HEAD, and either ContentLength is greater or equal to zero or SendChunked is true.
- ou --or-
KeepAlive é true, AllowWriteStreamBuffering é false, ContentLength é -1, SendChunked é false e Method é POST ou PUT.KeepAlive is true, AllowWriteStreamBuffering is false, ContentLength is -1, SendChunked is false, and Method is POST or PUT.
- ou --or- O HttpWebRequest tem um corpo de entidade, mas o método GetResponse() é chamado sem chamar o método GetRequestStream().The HttpWebRequest has an entity body but the GetResponse() method is called without calling the GetRequestStream() method.
- ou --or- O ContentLength é maior que zero, mas o aplicativo não grava todos os dados prometidos.The ContentLength is greater than zero, but the application does not write all of the promised data.
O validador de cache de solicitações indicou que a resposta para essa solicitação pode ser atendida no cache; no entanto, essa solicitação inclui dados a serem enviados ao 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. Solicitações que enviam dados não devem usar o cache.Requests that send data must not use the cache. Essa exceção poderá ocorrer se você estiver usando um validador de cache personalizado implementado incorretamente.This exception can occur if you are using a custom cache validator that is incorrectly implemented.
Abort() foi chamado anteriormente.Abort() was previously called.
- ou --or- O período de tempo limite da solicitação expirou.The time-out period for the request expired.
- ou --or- Ocorreu um erro ao processar a solicitação.An error occurred while processing the request.
Exemplos
O exemplo de código a seguir obtém a resposta para uma solicitação.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.
'...
'
'
Comentários
O GetResponse método retorna um WebResponse objeto que contém a resposta do recurso da Internet.The GetResponse method returns a WebResponse object that contains the response from the Internet resource. A instância real retornada é um HttpWebResponse e pode ser conversãoda a essa classe para acessar propriedades específicas de http.The actual instance returned is an HttpWebResponse, and can be typecast to that class to access HTTP-specific properties.
Um ProtocolViolationException é lançado em vários casos quando as propriedades definidas na HttpWebRequest classe estão em conflito.A ProtocolViolationException is thrown in several cases when the properties set on the HttpWebRequest class are conflicting. Essa exceção ocorrerá se um aplicativo definir a ContentLength propriedade e a SendChunked propriedade como e, true em seguida, enviar uma solicitação 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. Essa exceção ocorrerá se um aplicativo tentar enviar um bloco para um servidor que dá suporte apenas ao protocolo HTTP 1,0, no qual não há suporte para isso.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. Essa exceção ocorre se um aplicativo tentar enviar dados sem definir a ContentLength propriedade ou se o SendChunked false buffer estiver desabilitado e em uma conexão KeepAlive (a KeepAlive propriedade é true ).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).
Cuidado
Você deve chamar o Close método para fechar o fluxo e liberar a conexão.You must call the Close method to close the stream and release the connection. A falha em fazer isso pode fazer com que o aplicativo fique sem conexões.Failure to do so may cause your application to run out of connections.
Ao usar o método POST, você deve obter o fluxo de solicitação, gravar os dados a serem postados e fechar o fluxo.When using the POST method, you must get the request stream, write the data to be posted, and close the stream. Esse método bloqueia a espera pelo conteúdo a ser Postado; Se não houver nenhum tempo limite definido e você não fornecer conteúdo, o thread de chamada será bloqueado 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.
Observação
Várias chamadas para GetResponse retornar o mesmo objeto de resposta; a solicitação não é reemitida.Multiple calls to GetResponse return the same response object; the request is not reissued.
Observação
Seu aplicativo não pode misturar métodos síncronos e assíncronos para uma solicitação específica.Your application cannot mix synchronous and asynchronous methods for a particular request. Se você chamar o GetRequestStream método, deverá usar o GetResponse método para recuperar a resposta.If you call the GetRequestStream method, you must use the GetResponse method to retrieve the response.
Observação
Se um WebException for gerado, use as Response Status Propriedades e da exceção para determinar a resposta do servidor.If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.
Observação
Esse membro emite o rastreamento de informações quando você ativa o rastreamento de rede em seu aplicativo.This member outputs trace information when you enable network tracing in your application. Para obter mais informações, consulte rastreamento de rede na .NET Framework.For more information, see Network Tracing in the .NET Framework.
Observação
Por motivos de segurança, os cookies são desabilitados por padrão.For security reasons, cookies are disabled by default. Se você quiser usar cookies, use a CookieContainer propriedade para habilitar cookies.If you wish to use cookies, use the CookieContainer property to enable cookies.