Aracılığıyla paylaş


HttpWebRequest.BeginGetResponse(AsyncCallback, Object) Yöntem

Tanım

İnternet kaynağına zaman uyumsuz bir istek başlatır.

public:
 override IAsyncResult ^ BeginGetResponse(AsyncCallback ^ callback, System::Object ^ state);
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state);
public override IAsyncResult BeginGetResponse(AsyncCallback? callback, object? state);
override this.BeginGetResponse : AsyncCallback * obj -> IAsyncResult
Public Overrides Function BeginGetResponse (callback As AsyncCallback, state As Object) As IAsyncResult

Parametreler

callback
AsyncCallback

Temsilci AsyncCallback .

state
Object

Bu isteğin durum nesnesi.

Döndürülenler

Yanıt IAsyncResult için zaman uyumsuz isteğe başvuran.

Özel durumlar

Akışın kullanımda olduğu önceki bir çağrı BeginGetResponse(AsyncCallback, Object)

-veya-

TransferEncoding bir değere ayarlanır ve SendChunked şeklindedir false.

-veya-

İş parçacığı havuzunda iş parçacıkları tükeniyor.

Method GET veya HEAD şeklindedir ve ContentLength sıfırdan büyük veya SendChunked şeklindedir true.

-veya-

KeepAlive is true, AllowWriteStreamBuffering is falseve is ContentLength -1, SendChunked is false and Method is POST veya PUT.

-veya-

HttpWebRequest bir varlık gövdesine sahiptir, ancak BeginGetResponse(AsyncCallback, Object) yöntemi yöntemi çağrılmadan çağrılırBeginGetRequestStream(AsyncCallback, Object).

-veya-

ContentLength sıfırdan büyüktür, ancak uygulama söz verilen verilerin tümünü yazmaz.

Abort() daha önce çağrıldı.

Örnekler

Aşağıdaki kod örneği, bir İnternet kaynağı için zaman uyumsuz istekte bulunmak için yöntemini kullanır BeginGetResponse .

Not

Zaman uyumsuz istekler söz konusu olduğunda, istemci uygulamasının kendi zaman aşımı mekanizmasını uygulaması sorumluluğundadır. Aşağıdaki kod örneği bunun nasıl yapılacağını gösterir.

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;

public static class WebRequestAPMSample
{
    private const int BufferSize = 1024;

    private class RequestState
    {
        public StringBuilder ResponseBuilder { get; }
        public byte[] ReadBuffer { get; }
        public WebRequest Request { get; }
        public WebResponse Response { get; set; }
        public Stream ResponseStream { get; set; }
        public RequestState(WebRequest request)
        {
            ReadBuffer = new byte[BufferSize];
            ResponseBuilder = new StringBuilder();
            Request = request;
        }
        public void OnResponseBytesRead(int read) => ResponseBuilder.Append(Encoding.UTF8.GetString(ReadBuffer, 0, read));
    }

    public static ManualResetEvent allDone = new ManualResetEvent(false);
    

    public static void Main()
    {
        try
        {
            // Create a WebRequest object to the desired URL.
            WebRequest webRequest = WebRequest.Create("http://www.contoso.com");
            webRequest.Timeout = 10_000; // Set 10sec timeout.

            // Create an instance of the RequestState and assign the previous myHttpWebRequest
            // object to its request field.
            RequestState requestState = new RequestState(webRequest);

            // Start the asynchronous request.
            IAsyncResult result = webRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), requestState);

            // Wait for the response or for failure. The processing happens in the callback.
            allDone.WaitOne();

            // Release the WebResponse resources.
            requestState.Response?.Close();
        }
        catch (WebException e)
        {
            Console.WriteLine("\nMain(): WebException raised!");
            Console.WriteLine("\nMessage:{0}", e.Message);
            Console.WriteLine("\nStatus:{0}", e.Status);
            Console.WriteLine("Press any key to continue..........");
            Console.Read();
        }
        catch (Exception e)
        {
            Console.WriteLine("\nMain(): Exception raised!");
            Console.WriteLine("Source :{0} ", e.Source);
            Console.WriteLine("Message :{0} ", e.Message);
            Console.WriteLine("Press any key to continue..........");
            Console.Read();
        }
    }

    private static void HandleSyncResponseReadCompletion(IAsyncResult asyncResult)
    {
        RequestState requestState = (RequestState)asyncResult.AsyncState;
        Stream responseStream = requestState.ResponseStream;

        bool readComplete = false;
        while (asyncResult.CompletedSynchronously && !readComplete)
        {
            int read = responseStream.EndRead(asyncResult);
            if (read > 0)
            {
                requestState.OnResponseBytesRead(read);
                asyncResult = responseStream.BeginRead(requestState.ReadBuffer, 0, BufferSize, new AsyncCallback(ReadCallBack), requestState);
            }
            else
            {
                readComplete = true;
                HandleReadCompletion(requestState);
            }
        }
    }

    private static void ResponseCallback(IAsyncResult asynchronousResult)
    {
        try
        {
            // AsyncState is an instance of RequestState.
            RequestState requestState = (RequestState)asynchronousResult.AsyncState;
            WebRequest request = requestState.Request;
            requestState.Response = request.EndGetResponse(asynchronousResult);

            // Read the response into a Stream.
            Stream responseStream = requestState.Response.GetResponseStream();
            requestState.ResponseStream = responseStream;

            // Begin the Reading of the contents of the HTML page and print it to the console.
            IAsyncResult asynchronousReadResult = responseStream.BeginRead(requestState.ReadBuffer, 0, BufferSize, new AsyncCallback(ReadCallBack), requestState);
            HandleSyncResponseReadCompletion(asynchronousReadResult);
        }
        catch (WebException e)
        {
            Console.WriteLine("\nRespCallback(): Exception raised!");
            Console.WriteLine("\nMessage:{0}", e.Message);
            Console.WriteLine("\nStatus:{0}", e.Status);
            allDone.Set();
        }   
    }

    // Print the webpage to the standard output, close the stream and signal completion.
    private static void HandleReadCompletion(RequestState requestState)
    {
        Console.WriteLine("\nThe contents of the Html page are : ");
        if (requestState.ResponseBuilder.Length > 1)
        {
            string stringContent;
            stringContent = requestState.ResponseBuilder.ToString();
            Console.WriteLine(stringContent);
        }
        Console.WriteLine("Press any key to continue..........");
        Console.ReadLine();

        requestState.ResponseStream.Close();
        allDone.Set();
    }

    private static void ReadCallBack(IAsyncResult asyncResult)
    {
        if (asyncResult.CompletedSynchronously)
        {
            // To avoid recursive synchronous calls into ReadCallBack,
            // synchronous completion is handled at the BeginRead call-site.
            return;
        }

        try
        {
            RequestState requestState = (RequestState)asyncResult.AsyncState;
            Stream responseStream = requestState.ResponseStream;
            int read = responseStream.EndRead(asyncResult);
            // Read the HTML page and then print it to the console.
            if (read > 0)
            {
                requestState.OnResponseBytesRead(read);
                IAsyncResult asynchronousResult = responseStream.BeginRead(requestState.ReadBuffer, 0, BufferSize, new AsyncCallback(ReadCallBack), requestState);
                HandleSyncResponseReadCompletion(asynchronousResult);
            }
            else
            {
                HandleReadCompletion(requestState);
            }
        }
        catch (WebException e)
        {
            Console.WriteLine("\nReadCallBack(): Exception raised!");
            Console.WriteLine("\nMessage:{0}", e.Message);
            Console.WriteLine("\nStatus:{0}", e.Status);
            allDone.Set();
        }
    }
}

Açıklamalar

Dikkat

WebRequest, HttpWebRequest, ServicePointve WebClient kullanım dışıdır ve bunları yeni geliştirme için kullanmamalısınız. Bunun yerine HttpClient kullanın.

yöntemi, BeginGetResponse İnternet kaynağından bir yanıt için zaman uyumsuz bir istek başlatır. Zaman uyumsuz geri çağırma yöntemi, gerçek WebResponsedeğerini döndürmek için yöntemini kullanırEndGetResponse.

sınıfı üzerinde HttpWebRequest ayarlanan özellikler çakıştığında birkaç durumda A ProtocolViolationException oluşturulur. Bu özel durum, bir uygulama özelliğini ve SendChunked özelliğini olarak trueayarlar ContentLength ve ardından bir HTTP GET isteği gönderirse oluşur. Bu özel durum, uygulamanın öbeklenmiş olarak yalnızca HTTP 1.0 protokollerini destekleyen bir sunucuya göndermeye çalışması durumunda oluşur ve burada bu desteklenmez. Bu özel durum, bir uygulama özelliğini ayarlamadan ContentLength veri göndermeye çalışırsa veya falseSendChunked arabelleğe alma devre dışı bırakıldığında ve tutmalı bir bağlantıda (KeepAliveözelliği şudurtrue) oluşur:.

oluşturulursa WebException , sunucudan Response yanıtı belirlemek için özel durumun ve Status özelliklerini kullanın.

yöntemi, BeginGetResponse bu yöntemin zaman uyumsuz hale gelmesi için bazı zaman uyumlu kurulum görevlerinin (örneğin, DNS çözümlemesi, ara sunucu algılama ve TCP yuva bağlantısı) tamamlanmasını gerektirir. Sonuç olarak, bir hatanın özel durumu oluşmadan veya yöntem başarılı olmadan önce ilk zaman uyumlu kurulum görevlerini tamamlamak çok uzun sürebileceğinden (ağ ayarlarına bağlı olarak birkaç dakikaya kadar) bu yöntem hiçbir zaman kullanıcı arabirimi (UI) iş parçacığında çağrılmamalıdır.

İş parçacığı havuzu hakkında daha fazla bilgi edinmek için bkz. Yönetilen iş parçacığı havuzu.

Not

Uygulamanız belirli bir istek için zaman uyumlu ve zaman uyumsuz yöntemleri karıştıramaz. yöntemini çağırırsanız BeginGetRequestStream , yanıtı almak için yöntemini kullanmanız BeginGetResponse gerekir.

Not

Bu üye, uygulamanızda ağ izlemeyi etkinleştirdiğinizde izleme bilgilerini döndürür. Daha fazla bilgi için bkz. .NET Framework'te Ağ İzleme.

Şunlara uygulanır

Ayrıca bkz.