Freigeben über


HttpWebRequest.BeginGetResponse Method

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Begins an asynchronous request to an Internet resource.

Namespace:  System.Net
Assembly:  System.Net (in System.Net.dll)

Syntax

'Declaration
Public Overrides Function BeginGetResponse ( _
    callback As AsyncCallback, _
    state As Object _
) As IAsyncResult
public override IAsyncResult BeginGetResponse(
    AsyncCallback callback,
    Object state
)

Parameters

Return Value

Type: System.IAsyncResult
An IAsyncResult that references the asynchronous request for a response.

Exceptions

Exception Condition
InvalidOperationException

The stream is already in use by a previous call to BeginGetResponse

-or-

The thread pool is running out of threads.

NotImplementedException

This method is not implemented.

NotSupportedException

The callback parameter is nulla null reference (Nothing in Visual Basic).

ProtocolViolationException

Method is GET.

WebException

Abort was previously called.

Remarks

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.

If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.

In the case of asynchronous requests, it is the responsibility of the client application to implement its own time-out mechanism.

The IAsyncResult returned by the BeginGetResponse method does not support the AsyncWaitHandle property. If an application tries to access the AsyncWaitHandle property, a NotSupportedException is thrown.

The AllowReadStreamBuffering property affects when the callback from BeginGetResponse method is called. When the AllowReadStreamBuffering property is true, the callback is raised once the entire stream has been downloaded into memory. When the AllowReadStreamBuffering property is false, the callback is raised as soon as the stream is available for reading which may be before all data has arrived.

Examples

public class RequestState
{
  // This class stores the State of the request.
  const int BUFFER_SIZE = 1024;
  public StringBuilder requestData;
  public byte[] BufferRead;
  public HttpWebRequest request;
  public HttpWebResponse response;
  public Stream streamResponse;

  public RequestState()
  {
    BufferRead = new byte[BUFFER_SIZE];
    requestData = new StringBuilder("");
    request = null;
    streamResponse = null;
  }
}

public class Example
{

  public static ManualResetEvent allDone= new ManualResetEvent(false);
  const int BUFFER_SIZE = 1024;

  public static void Demo(System.Windows.Controls.TextBlock outputBlock)
  {
  try
  {      

    System.Uri uri = new Uri("https://www.contoso.com");
    // Create a HttpWebrequest object to the desired URL.
    HttpWebRequest myHttpWebRequest1= (HttpWebRequest)WebRequest.Create(uri);

    // Create an instance of the RequestState and assign the previous myHttpWebRequest1
    // object to it's request field.  
    RequestState myRequestState = new RequestState();  
    myRequestState.request = myHttpWebRequest1;


    // Start the asynchronous request.
    IAsyncResult result=
      (IAsyncResult) myHttpWebRequest1.BeginGetResponse(new AsyncCallback(RespCallback),myRequestState);

  }
  catch(WebException e)
  {
    outputBlock.Text += "\nException raised!\n";
    outputBlock.Text += "Message: ";
    outputBlock.Text += e.Message;
    outputBlock.Text += "\nStatus: ";
    outputBlock.Text += e.Status;
    outputBlock.Text += "\n";
  }
  catch(Exception e)
  {
    outputBlock.Text += "\nException raised!\n";
    outputBlock.Text += "\nMessage: ";
    outputBlock.Text += e.Message;
    outputBlock.Text += "\n";
  }
}
private static void RespCallback(IAsyncResult asynchronousResult)
{  
  try
  {
    // State of request is asynchronous.
    RequestState myRequestState=(RequestState) asynchronousResult.AsyncState;
    HttpWebRequest  myHttpWebRequest2=myRequestState.request;
    myRequestState.response = (HttpWebResponse) myHttpWebRequest2.EndGetResponse(asynchronousResult);

    // Read the response into a Stream object.
    Stream responseStream = myRequestState.response.GetResponseStream();
    myRequestState.streamResponse=responseStream;

    // Begin the Reading of the contents of the HTML page and print it to the console.
    IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
  }
  catch(WebException e)
  {
    // Need to handle the exception
  }
}
private static  void ReadCallBack(IAsyncResult asyncResult)
{
  try
  {

    RequestState myRequestState = (RequestState)asyncResult.AsyncState;
    Stream responseStream = myRequestState.streamResponse;
    int read = responseStream.EndRead( asyncResult );
    // Read the HTML page and then do something with it
    if (read > 0)
    {
      myRequestState.requestData.Append(Encoding.UTF8.GetString(myRequestState.BufferRead, 0, read));
      IAsyncResult asynchronousResult = responseStream.BeginRead( myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
    }
    else
    {
      if(myRequestState.requestData.Length>1)
      {
        string stringContent;
        stringContent = myRequestState.requestData.ToString();
        // do something with the response stream here
      }

      responseStream.Close();
      allDone.Set();

    }

  }
  catch(WebException e)
  {
    // Need to handle the exception
  }

}

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.