Udostępnij za pośrednictwem


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

WebResponse, który zawiera odpowiedź z zasobu internetowego.

Wyjątki

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

-lub-

TransferEncoding jest ustawiona na wartość, a SendChunked jest false.

Method to GET lub HEAD, a ContentLength jest większa lub równa zero lub SendChunked jest true.

-lub-

KeepAlive jest true, AllowWriteStreamBuffering jest false, ContentLength jest -1, SendChunked jest false, a Method jest POST lub PUT.

-lub-

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

-lub-

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 zawiera dane do wysłania na serwer. Żą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() wcześniej wywoływano.

-lub-

Limit czasu żądania wygasł.

-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

Ostrożność

WebRequest, HttpWebRequest, ServicePointi WebClient są przestarzałe i nie należy ich używać do tworzenia nowych aplikacji. Zamiast tego użyj HttpClient.

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

ProtocolViolationException jest zgłaszany w kilku przypadkach, gdy właściwości ustawione w klasie HttpWebRequest są sprzeczne. Ten wyjątek występuje, jeśli aplikacja ustawia właściwość ContentLength i właściwość SendChunked na true, a następnie wysyła żądanie HTTP GET. Ten wyjątek występuje, jeśli aplikacja próbuje wysłać fragmentowane 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 właściwości ContentLength lub SendChunked jest false podczas buforowania jest wyłączona, a w połączeniu na żywo (właściwość KeepAlive jest true).

Ostrożność

Należy wywołać metodę Close, aby zamknąć strumień i zwolnić połączenie. Niepowodzenie tej czynności 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.

Nuta

Wiele wywołań GetResponse zwraca ten sam obiekt odpowiedzi; żądanie nie zostanie ponownie zwrócone.

Nuta

Aplikacja nie może mieszać metod synchronicznych i asynchronicznych dla określonego żądania. Jeśli wywołasz metodę GetRequestStream, musisz użyć metody GetResponse, aby pobrać odpowiedź.

Nuta

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

Nuta

Ten element członkowski generuje informacje śledzenia po włączeniu śledzenia sieci w aplikacji. Aby uzyskać więcej informacji, zobacz Śledzenie sieci w programie .NET Framework.

Nuta

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

Dotyczy

Zobacz też