HttpWebRequest.GetResponse Metoda

Definicja

Zwraca odpowiedź z zasobu internetowego.

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

Zwraca

Element WebResponse zawierający odpowiedź z zasobu internetowego.

Wyjątki

Strumień jest już używany przez poprzednie wywołanie metody BeginGetResponse(AsyncCallback, Object).

-lub-

TransferEncoding jest ustawiona na wartość i SendChunked ma falsewartość .

Method to GET lub HEAD, a ContentLength wartość jest większa lub równa zero lub SendChunked jest truerówna .

-lub-

KeepAlivetrueis , AllowWriteStreamBuffering is false, ContentLength is -1, SendChunked is false, i Method is POST lub PUT.

-lub-

Obiekt HttpWebRequest ma treść jednostki, ale GetResponse() metoda jest wywoływana bez wywoływania GetRequestStream() metody .

-lub-

Wartość ContentLength jest większa niż zero, ale aplikacja nie zapisuje wszystkich obiecanych danych.

Moduł sprawdzania poprawności pamięci podręcznej żądań wskazał, że odpowiedź na to żądanie może być obsługiwana z pamięci podręcznej; jednak to żądanie obejmuje dane, które mają być wysyłane do serwera. Żądania wysyłające dane nie mogą używać pamięci podręcznej. Ten wyjątek może wystąpić, jeśli używasz niestandardowego modułu sprawdzania poprawności pamięci podręcznej, który jest niepoprawnie zaimplementowany.

Abort() był wcześniej wywoływany.

-lub-

Upłynął limit czasu dla żądania.

-lub-

Wystąpił błąd podczas przetwarzania żądania.

Przykłady

Poniższy przykład kodu pobiera odpowiedź na żądanie.

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

Uwagi

Metoda GetResponse zwraca WebResponse obiekt zawierający odpowiedź z zasobu internetowego. Zwracane wystąpienie jest wystąpieniem HttpWebResponsetypu i może być typucast do tej klasy w celu uzyskania dostępu do właściwości specyficznych dla protokołu HTTP.

Element A ProtocolViolationException jest zgłaszany w kilku przypadkach, gdy właściwości ustawione w HttpWebRequest klasie są sprzeczne. Ten wyjątek występuje, jeśli aplikacja ustawia ContentLength właściwość i SendChunked właściwość na true, a następnie wysyła żądanie HTTP GET. Ten wyjątek występuje, jeśli aplikacja próbuje wysłać fragment do serwera, który obsługuje tylko protokół HTTP 1.0, gdzie nie jest to obsługiwane. Ten wyjątek występuje, jeśli aplikacja próbuje wysłać dane bez ustawienia ContentLength właściwości lub SendChunked jest false wtedy, gdy buforowanie jest wyłączone i na połączeniu keepalive ( KeepAlive właściwość to true).

Przestroga

Należy wywołać metodę , Close aby zamknąć strumień i zwolnić połączenie. Nie można tego zrobić, może spowodować, że aplikacja zabraknie połączeń.

W przypadku korzystania z metody POST należy pobrać strumień żądania, zapisać dane do opublikowania i zamknąć strumień. Ta metoda blokuje oczekiwanie na opublikowanie zawartości; jeśli nie ma ustawionego limitu czasu i nie udostępniasz zawartości, wątek wywołujący blokuje się na czas nieokreślony.

Uwaga

Wiele wywołań, aby GetResponse zwrócić ten sam obiekt odpowiedzi. Żądanie nie jest ponownie wywoływane.

Uwaga

Aplikacja nie może mieszać metod synchronicznych i asynchronicznych dla określonego żądania. W przypadku wywołania GetRequestStream metody należy użyć GetResponse metody , aby pobrać odpowiedź.

Uwaga

Jeśli element WebException zostanie zgłoszony, użyj Response właściwości i Status wyjątku, aby określić odpowiedź z serwera.

Uwaga

Ten element członkowski generuje informacje ze śledzenia pod warunkiem włączenia funkcji śledzenia sieci w aplikacji. Aby uzyskać więcej informacji, zobacz Śledzenie sieci w .NET Framework.

Uwaga

Ze względów bezpieczeństwa pliki cookie są domyślnie wyłączone. Jeśli chcesz używać plików cookie, użyj CookieContainer właściwości , aby włączyć pliki cookie.

Dotyczy

Zobacz też