0 out of 8 rated this helpful - Rate this topic

HttpWebRequest.BeginGetResponse Method

Begins an asynchronous request to an Internet resource.

Namespace:  System.Net
Assembly:  System.Net (in System.Net.dll)
public override IAsyncResult BeginGetResponse(
	AsyncCallback callback,
	Object state
)

Parameters

callback
Type: System.AsyncCallback
The AsyncCallback delegate
state
Type: System.Object
The state object for this request.

Return Value

Type: System.IAsyncResult
An IAsyncResult that references the asynchronous request for a response.
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 null.

ProtocolViolationException

Method is GET.

WebException

Abort was previously called.

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.


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("http://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
  }

}


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

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

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
So Much for Code Reviews....
title says it all...  Tech Writers have failed yet again.
Really poor example
A real poor example all I could say.. broken at every tids and bits.  $0$0 $0 $0More disappointing not yet fixed even after a year.$0
how to use the example in Windows Phone 7
For those using a Windows Phone 7 create this class;

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;
  }
}


And then comment the following lines:

//allDone.WaitOne();
// Release the HttpWebResponse resource.
//myRequestState.response.Close();
.....
//allDone.Set();


Completely broken
Even without the incomplete code this sample is horribly broken on Silverlight. $0 $0 The WaitOne() will block the the UI thread if called from it, preventing the WebRequest from ever completing. This is because HttpWebRequest returns the response on the UI thread no matter what thread the request is initiated from. There seems to be no way to block the UI Thread **AND** await the response, because the call pretends to be async, but in reality is on the UI Thread.
WebClient works if you need simplicity
You can perform an asychronous request/response by using the much simpler WebClient. It's not for everything but great for simple requests and can be setup in few lines of code.

This example is from SL2 but it works in SL4:
http://wildermuth.com/2008/09/27/WebClient_vs_WebRequest_in_Silverlight_2

Lastly, this a very poor MSDN article. Including non-library class RequestState, without including the class, and referencing what I can only assume is a ManualResetEvent (or WaitHandle) without the declaration is inexcusable.

Please correct this.
The definition of the RequestState class is missing

The sample is incomplete if the platform is Silverlight (the definition of the class RequestState is missing). You can find it if you switch the platform to .Net Framework 4. Here is the definition copied from the .Net Framework 4 page:

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;
  }
}

missing the RequestState class
I could be wrong but to me this looks like someone did a bad job of copying and pasting from http://stackoverflow.com/questions/295557/c-downloading-a-url-with-timeout
Who are the helping?
What an embarassing example.
Getting hard
I'm also a bit confuse how hard it is to download a simple file from the web.

I understand that you can't have super simple syncronious method sush as DownloadAsString

but I would rather imagine something with a simple call back from a single object.

Better help us to find way to do simple stuff in Silverlight or we may in fact go back to Flash programming...
Better Example Code
Can we get a better example? What is a RequestState object? What is the need for so much code to get a HTTP response from a Server? Makes me want to code Flex

Looking at the code, it is designed to transfer a reponse from a URI that may consist of multiple segments. It uses two call back routines to accomplish this. The first call back routine begins by placing the initial response segment into a buffer, and then allows the second call back routine to add subsequent segments to the buffer.

To confuse the matter further the "allDone.WaitOne()" routine
is omitted.

This example requires sufficient knowledge of async. processing.
It is a good example if you wish to learn about async. processing.
However, some persons may find it a difficult challenge. It may go a bit too far for some.