Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

WebRequest.BeginGetRequestStream Method

When overridden in a descendant class, provides an asynchronous version of the GetRequestStream method.

[Visual Basic]
Public Overridable Function BeginGetRequestStream( _
   ByVal callback As AsyncCallback, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public virtual IAsyncResult BeginGetRequestStream(
 AsyncCallback callback,
 object state
);
[C++]
public: virtual IAsyncResult* BeginGetRequestStream(
 AsyncCallback* callback,
 Object* state
);
[JScript]
public function BeginGetRequestStream(
   callback : AsyncCallback,
 state : Object
) : IAsyncResult;

Parameters

callback
The AsyncCallback delegate.
state
An object containing state information for this asynchronous request.

Return Value

An IAsyncResult that references the asynchronous request.

Exceptions

Exception Type Condition
NotSupportedException Any attempt is made to access the method, when the method is not overridden in a descendant class.

Remarks

The BeginGetRequestStream method starts an asynchronous request for a stream used to send data to an Internet resource. The callback method that implements the AsyncCallback delegate uses the EndGetRequestStream method to return the request stream.

Note   The WebRequest class is an abstract (MustInherit in Visual Basic) class. The actual behavior of WebRequest instances at run time is determined by the descendant class returned by the WebRequest.Create method. For more information about default values and exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.

Example

[Visual Basic, C#, C++] The following example uses the BeginGetRequestStream to asynchronously obtain the request stream.

[Visual Basic] 

        ' Create a new request to the mentioned URL.
            Dim myWebRequest As WebRequest = WebRequest.Create("http://www.contoso.com/codesnippets/next.asp")

            ' Create an instance of the RequestState and assign 'myWebRequest' to it's request field.            
            Dim myRequestState As New RequestState()
            myRequestState.request = myWebRequest
            myWebRequest.ContentType = "application/x-www-form-urlencoded"

            ' Set the 'Method' prperty  to 'POST' to post data to a Uri.
            myRequestState.request.Method = "POST"
            myRequestState.request.ContentType = "application/x-www-form-urlencoded"

            ' Start the Asynchronous 'BeginGetRequestStream' method call.    
            Dim r As IAsyncResult = CType(myWebRequest.BeginGetRequestStream(AddressOf ReadCallback, myRequestState), IAsyncResult)

            ' Assign the response object of 'WebRequest' to a 'WebResponse' variable.
            Dim myWebResponse As WebResponse = myWebRequest.GetResponse()
            Console.WriteLine(ControlChars.Cr + "The string entered has been successfully posted to the Uri")
            Console.WriteLine("Please wait for the response.......")
            Dim streamResponse As Stream = myWebResponse.GetResponseStream()
            Dim streamRead As New StreamReader(streamResponse)
            Dim readBuff(256) As [Char]
            Dim count As Integer = streamRead.Read(readBuff, 0, 256)
            Console.WriteLine(ControlChars.Cr + "The contents of the HTML page are ")
            While count > 0
                Dim outputData As New [String](readBuff, 0, count)
                Console.WriteLine(outputData)
                count = streamRead.Read(readBuff, 0, 256)
            End While

           ' Close the Stream Object.
        streamResponse.Close()
        streamRead.Close()
        allDone.WaitOne()    

        ' Release the HttpWebResponse Resource.
         myWebResponse.Close()    
        Catch e As WebException
            Console.WriteLine(ControlChars.Cr + "WebException Caught!")
            Console.WriteLine("Message :{0}", e.Message)
        Catch e As Exception
            Console.WriteLine(ControlChars.Cr + "Exception Caught!")
            Console.WriteLine("Message :{0}", e.Message)
        End Try
    End Sub ' Main
     
    Private Shared Sub ReadCallback(asynchronousResult As IAsyncResult)
        Try

            ' State of request is set to asynchronous.
            Dim myRequestState As RequestState = CType(asynchronousResult.AsyncState, RequestState)
            Dim myWebRequest2 As WebRequest = myRequestState.request

            ' End of the Asynchronus request.
            Dim streamResponse As Stream = myWebRequest2.EndGetRequestStream(asynchronousResult)

            ' Create a string that is to be posted to the uri.
            Console.WriteLine(ControlChars.Cr + "Please enter a string to be posted to (http://www.contoso.com/codesnippets/next.asp) Uri:")
            Dim inputData As String = Console.ReadLine()
            Dim postData As String = "firstone" + ChrW(61) + inputData
            Dim encoder As New ASCIIEncoding()

            ' Convert  the string into a byte array.
            Dim ByteArray As Byte() = encoder.GetBytes(postData)

            ' Write data to the stream.
            streamResponse.Write(ByteArray, 0, postData.Length)
            streamResponse.Close()
            allDone.Set()

        Catch e As WebException
            Console.WriteLine(ControlChars.Cr + "WebException Caught!")
            Console.WriteLine("Message :{0}", e.Message)
        Catch e As Exception
            Console.WriteLine(ControlChars.Cr + "Exception Caught!")
            Console.WriteLine("Message :{0}", e.Message)
        End Try

    End Sub ' ReadCallback 

[C#] 
// Create a new request to the mentioned URL.    
WebRequest myWebRequest= WebRequest.Create("http://www.contoso.com");

// Create an instance of the RequestState and assign 'myWebRequest' to it's request field.    
RequestState myRequestState = new RequestState();
myRequestState.request = myWebRequest;            
myWebRequest.ContentType="application/x-www-form-urlencoded";

// Set the 'Method' prperty  to 'POST' to post data to a Uri.
myRequestState.request.Method="POST";
myRequestState.request.ContentType="application/x-www-form-urlencoded";

// Start the Asynchronous 'BeginGetRequestStream' method call.    
IAsyncResult r=(IAsyncResult) myWebRequest.BeginGetRequestStream(new AsyncCallback(ReadCallback),myRequestState);            

// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
WebResponse myWebResponse=myWebRequest.GetResponse();
Console.WriteLine("\nThe string entered has been successfully posted to the Uri");    
Console.WriteLine("Please wait for the response.......");

Stream streamResponse=myWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader( streamResponse );
Char[] readBuff = new Char[256];
int count = streamRead.Read( readBuff, 0, 256 );
Console.WriteLine("\nThe contents of the HTML page are ");    

while (count > 0) 
{
    String outputData = new String(readBuff, 0, count);
    Console.Write(outputData);
    count = streamRead.Read(readBuff, 0, 256);
}

// Close the Stream Object.
streamResponse.Close();
streamRead.Close();
allDone.WaitOne();    

// Release the HttpWebResponse Resource.
myWebResponse.Close();            

        }
        catch(Exception e)
        {
Console.WriteLine(e.ToString());
        }

    }
    private static void ReadCallback(IAsyncResult asynchronousResult)
    {    
        try
        {

// State of request is set to asynchronous.
RequestState myRequestState=(RequestState) asynchronousResult.AsyncState;
WebRequest  myWebRequest2=myRequestState.request;

// End of the Asynchronus request.
Stream streamResponse=myWebRequest2.EndGetRequestStream(asynchronousResult);

// Create a string that is to be posted to the uri.
Console.WriteLine("\nPlease enter a string to be posted to (http://www.contoso.com) Uri:");
string inputData=Console.ReadLine();
string postData="firstone="+inputData;
ASCIIEncoding encoder = new ASCIIEncoding();

// Convert  the string into a byte array.
byte[] ByteArray = encoder.GetBytes(postData);

// Write data to the stream.
streamResponse.Write(ByteArray,0,postData.Length);
streamResponse.Close();        
allDone.Set();
        }
        catch(Exception e)
        {
Console.WriteLine(e.ToString());
        }
    }

[C++] 
// Create a new request to the mentioned URL.
WebRequest* myWebRequest= WebRequest::Create(S"http://www.contoso.com");

// Create an instance of the RequestState and assign 'myWebRequest' to its request field.
RequestState* myRequestState = new RequestState();
myRequestState->request = myWebRequest;
myWebRequest->ContentType=S"application/x-www-form-urlencoded";

// Set the 'Method' prperty  to 'POST' to post data to a Uri.
myRequestState->request->Method=S"POST";
myRequestState->request->ContentType=S"application/x-www-form-urlencoded";

// Start the Asynchronous 'BeginGetRequestStream' method call.
IAsyncResult* r = 
   dynamic_cast<IAsyncResult*> (myWebRequest->BeginGetRequestStream(new AsyncCallback(r, 
   WebRequest_BeginGetRequeststream::ReadCallback), myRequestState));

// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
WebResponse* myWebResponse = myWebRequest->GetResponse();
Console::WriteLine(S"\nThe String* entered has been successfully posted to the Uri");
Console::WriteLine(S"Please wait for the response.......");

Stream* streamResponse = myWebResponse->GetResponseStream();
StreamReader* streamRead = new StreamReader(streamResponse);
Char readBuff[] = new Char[256];
int count = streamRead->Read(readBuff, 0, 256);
Console::WriteLine(S"\nThe contents of the HTML page are ");

while (count > 0) {
   String* outputData = new String(readBuff, 0, count);
   Console::Write(outputData);
   count = streamRead->Read(readBuff, 0, 256);
}

// Close the Stream Object.
streamResponse->Close();
streamRead->Close();
WebRequest_BeginGetRequeststream::allDone->WaitOne();

// Release the HttpWebResponse Resource.
myWebResponse->Close();

   } catch (Exception* e) {
Console::WriteLine(e);
   }
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework, Common Language Infrastructure (CLI) Standard

See Also

WebRequest Class | WebRequest Members | System.Net Namespace | EndGetRequestStream | Making Asynchronous Requests

Show:
© 2014 Microsoft