HttpWebRequest.BeginGetResponse(AsyncCallback, Object) Method
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Begins an asynchronous request to an Internet resource.
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
Parameters
- callback
- AsyncCallback
The AsyncCallback delegate.
- state
- Object
The state object for this request.
Returns
An IAsyncResult that references the asynchronous request for a response.
Exceptions
The stream is already in use by a previous call to BeginGetResponse(AsyncCallback, Object)
-or-
TransferEncoding is set to a value and SendChunked is false
.
-or-
The thread pool is running out of threads.
Method is GET or HEAD, and either ContentLength is greater than zero or SendChunked is true
.
-or-
KeepAlive is true
, AllowWriteStreamBuffering is false
, and either ContentLength is -1, SendChunked is false
and Method is POST or PUT.
-or-
The HttpWebRequest has an entity body but the BeginGetResponse(AsyncCallback, Object) method is called without calling the BeginGetRequestStream(AsyncCallback, Object) method.
-or-
The ContentLength is greater than zero, but the application does not write all of the promised data.
Abort() was previously called.
Examples
The following code example uses the BeginGetResponse method to make an asynchronous request for an Internet resource.
Note
In the case of asynchronous requests, it is the responsibility of the client application to implement its own time-out mechanism. The following code example shows how to do it.
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();
}
}
}
Remarks
Caution
WebRequest
, HttpWebRequest
, ServicePoint
, and WebClient
are obsolete, and you shouldn't use them for new development. Use HttpClient instead.
The BeginGetResponse method starts an asynchronous request for a response from the Internet resource. The asynchronous callback method uses the EndGetResponse method to return the actual WebResponse.
A ProtocolViolationException is thrown in several cases when the properties set on the HttpWebRequest class are conflicting. This exception occurs if an application sets the ContentLength property and the SendChunked property to true
, and then sends an HTTP GET request. 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. 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
).
If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.
The BeginGetResponse method requires some synchronous setup tasks to complete (DNS resolution, proxy detection, and TCP socket connection, for example) before this method becomes asynchronous. As a result, this method should never be called on a user interface (UI) thread because it might take considerable time (up to several minutes depending on network settings) to complete the initial synchronous setup tasks before an exception for an error is thrown or the method succeeds.
To learn more about the thread pool, see The managed thread pool.
Note
Your application cannot mix synchronous and asynchronous methods for a particular request. If you call the BeginGetRequestStream method, you must use the BeginGetResponse method to retrieve the response.
Note
This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in the .NET Framework.