Asynchronous HTTP Model


As weve seen with most other classes, the Web request-response classes (both the HTTP-specific classes as well as the generic Web classes) offer an asynchronous I/O pattern for retrieving the request stream and the response. The asynchronous Web pattern is useful when issuing multiple Web requests concurrently from a single application as well as for maximizing performance.

The first asynchronous method is BeginGetRequestStream , which is used for HTTP methods other than GET and HEAD . When this asynchronous request is issued, the callback is invoked and the request stream can be retrieved from the request object to send data associated with the Web request. If BeginGetRequestStream is invoked on a Web request whose method is GET or HEAD , a ProtocolViolationException exception is thrown. The BeginGetRequestStream is most commonly used with the POST method, as shown in the following example:

C#

 //Commonstateinformation publicclassHttpState { publicHttpWebRequesthttpRequest; publicHttpWebResponsehttpResponse; } publicclassAsyncPost { publicvoidDoAsyncPost() { try { HttpStatehttpRequestState=newHttpState(); //Setuptherequest httpRequestState.httpRequest= (HttpWebRequest)WebRequest.Create("http://www.microsoft.com/"); httpRequestState.httpRequest.Method= "POST"; httpRequestState.httpRequest.ContentType=  "application/x-www-form-urlencoded"; //Posttheasyncoperation IAsyncResultar= httpRequestState.httpRequest.BeginGetRequestStream(newAsyncCallback(HttpRequestStreamCallback), httpRequestState); //Processtheresponsestream httpRequestState.httpResponse= (HttpWebResponse) httpRequestState.httpRequest.GetResponse(); //Retrievetheresponsestream StreamReaderresponseStream=newStreamReader(httpRequestState.httpResponse.GetResponseStream()); //Receivetheresponse httpRequestState.httpResponse.Close(); } catch(Exceptionex) { Console.WriteLine("Exceptionoccurred:{0}",ex.Message); } } privatestaticvoidHttpRequestStreamCallback(IAsyncResultar) { try { //Stateofrequestissettoasynchronous. HttpStatehttpRequestState=(HttpState)ar.AsyncState; //EndoftheAsynchronousrequest. StreamstreamResponse= httpRequestState.httpRequest.EndGetRequestStream(ar); byte[]postData=newbyte[1024]; //Setupdatatowriteontherequeststream streamResponse.Write(postData,0,postData.Length); streamResponse.Close(); } catch(Exceptionex) { Console.WriteLine(ex.ToString()); } } } 

Visual Basic .NET

 


Network Programming for the Microsoft. NET Framework
Network Programming for the MicrosoftВ® .NET Framework (Pro-Developer)
ISBN: 073561959X
EAN: 2147483647
Year: 2003
Pages: 121

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net