HttpWebRequest.BeginGetResponse(AsyncCallback, Object) Yöntem
Tanım
Önemli
Bazı bilgiler ürünün ön sürümüyle ilgilidir ve sürüm öncesinde önemli değişiklikler yapılmış olabilir. Burada verilen bilgilerle ilgili olarak Microsoft açık veya zımni hiçbir garanti vermez.
İ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
AsyncCallback temsilcisi.
- state
- Object
Bu isteğin durum nesnesi.
Döndürülenler
Yanıt için zaman uyumsuz isteğe başvuran bir IAsyncResult.
Özel durumlar
Akış, önceki bir BeginGetResponse(AsyncCallback, Object) çağrısı tarafından zaten kullanılıyor
-veya-
TransferEncoding bir değere ayarlanır ve SendChunkedfalse.
-veya-
İş parçacığı havuzunda iş parçacıkları tükeniyor.
Method GET veya HEAD'dir ve ContentLength sıfırdan büyük veya SendChunkedtrue.
-veya-
KeepAlive
true, AllowWriteStreamBufferingfalseve ContentLength -1, SendChunkedfalse ve Method POST veya PUT şeklindedir.
-veya-
HttpWebRequest bir varlık gövdesi vardır, ancak BeginGetResponse(AsyncCallback, Object) yöntemi BeginGetRequestStream(AsyncCallback, Object) yöntemi çağrılmadan çağrılır.
-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, İnternet kaynağı için zaman uyumsuz istekte bulunmak için BeginGetResponse yöntemini kullanır.
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.
BeginGetResponse yöntemi, İnternet kaynağından gelen bir yanıt için zaman uyumsuz bir istek başlatır. Zaman uyumsuz geri çağırma yöntemi, gerçek WebResponsedöndürmek için EndGetResponse yöntemini kullanır.
HttpWebRequest sınıfında ayarlanan özellikler çakıştığında birkaç durumda bir ProtocolViolationException oluşturulur. Bu özel durum, bir uygulama ContentLength özelliğini ve SendChunked özelliğini trueolarak ayarlar 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 ContentLength özelliğini ayarlamadan veri göndermeye çalışırsa veya arabelleğe alma devre dışı bırakıldığında ve tutmalı bir bağlantıda (KeepAlive özelliği true) SendChunkedfalse.
Bir WebException oluşturulursa, sunucudan gelen yanıtı belirlemek için özel durumun Response ve Status özelliklerini kullanın.
BeginGetResponse yöntemi, 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. BeginGetRequestStream yöntemini çağırırsanız, yanıtı almak için BeginGetResponse yöntemini kullanmanız 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
Şunlara uygulanır
Ayrıca bkz.
- DefaultProxy Öğesi (Ağ Ayarları)