FCL small application series ---- how to use APM to implement httpwebrequest asynchronous sending and receiving

Source: Internet
Author: User
Tags apm urlencode

APM (asynchronous programming model) can be seen everywhere in. NET programming. The httpwebrequest class also implements APM, which can be used by users. I did a small experiment today and summarize it. Let's take a look at the code first.

Using system; <br/> using system. collections. generic; <br/> using system. LINQ; <br/> using system. text; <br/> using system. web; <br/> using system. net; <br/> using system. io; <br/> using system. windows. forms; </P> <p> namespace consoleapplication1 <br/> {<br/> class Program <br/>{< br/> static void main (string [] ARGs) <br/> {<br/> console. writeline (<br/> system. threading. thread. currentthread. managedthread Id. tostring (); <br/> xqhttpclient XC = new xqhttpclient (); <br/> xqformdata XF = new xqformdata (); <br/> XF. add ("username", "username"); <br/> XF. add ("password", "User Password"); <br/> XF. add ("loginsubmit", "login"); <br/> Int J = 0; <br/> for (j = 0; j <200; j ++) <br/>{< br/> XC. sendpostrequest ("http://blog.runsky.com/batch.login.php? Action = login ", XF. formdata); <br/> XC. sendgetrequest ("http://www.baidu.com"); <br/>}< br/> console. writeline ("main thread ......................... "); <br/> system. threading. thread. sleep (1000); <br/>}< br/> // construct form data, and urlencoded <br/> class xqformdata <br/>{< br/> Public xqformdata (encoding e) <br/>{< br/> This. formencoding = E; <br/>}< br/> Public xqformdata () <br/>{< br/> This. formenc ODing = encoding. getencoding ("gb2312 "); <br/>}< br/> Public String formdata <br/>{< br/> Get <br/>{< br/> return Str. substring (0, str. length-1); <br/>}< br/> set <br/>{< br/>}< br/> private encoding formencoding; <br/> private string STR; <br/> Public void add (string name, string value) <br/>{< br/> STR + = httputility. urlencode (name, this. formencoding); <br/> STR + = "="; <br/> Str + = Httputility. urlencode (value, encoding. getencoding ("gb2312"); <br/> STR + = "&"; <br/>}< br/> // <summary> <br/> // HTTP common client <br/> /// </Summary> <br/> class xqhttpclient <br/>{< br/> // server-side encoding method utf8/gb2312 <br/> private encoding encodingserver = encoding. getencoding ("gb2312"); <br/> private string struri; // request line, Unicode representation of urlencoded <br/> private string strformdata; // form data, urlencoe Unicode representation of D <br/> cookiecontainer currentcookiecontainer = new cookiecontainer (); // The current cookie container <br/> private string strresponsebody = ""; // The message body returned by the server </P> <p> // reload <br/> Public void sendpostrequest (string Uri, string formdata) <br/>{< br/> This. struri = URI; <br/> This. strformdata = formdata; <br/> sendpostrequest (); <br/>}< br/> // reload <br/> Public void sendgetrequest (string URI) <br/>{< br/> th Is. struri = URI; <br/> sendgetrequest (); <br/>}< br/> // After begingetresponse is completed, other CLR threads execute the command <br/> Public void getresponsedone (object state) // The State is automatically assigned to iresult <br/>{< br/> console. writeline ("getresponsedone:" + <br/> system. threading. thread. currentthread. managedthreadid. tostring (); <br/> try <br/>{< br/> iasyncresult IR = (iasyncresult) State; <br/> httpwebrequest Req = (httpwebrequest) IR. asyn Cstate; <br/> httpwebresponse resp = (httpwebresponse) (req. endgetresponse (IR); </P> <p> // read the message header </P> <p> // read the message body <br/> stream responsestream = resp. getresponsestream (); <br/> streamreader sr = new streamreader (responsestream, this. encodingserver); </P> <p> while (Sr. peek ()> = 0) <br/>{< br/> char [] Recv = new char [1024]; <br/> Sr. read (Recv, 0, Recv. length); <br/> strresponsebody + = new string (Recv ); <Br/>}< br/> catch (exception e) <br/>{< br/> console. writeline (E. tostring (); <br/>}< br/> // console. writeline (this. strresponsebody); <br/>}< br/> // send a GET request <br/> Public void sendgetrequest () <br/>{< br/> try <br/> {<br/> httpwebrequest Req = (httpwebrequest) webrequest. create (struri); <br/> req. method = "get"; <br/> req. cookiecontainer = This. currentcookiecontainer; </P> <p> // send and retrieve the server Server Response <br/> // APM version <br/> req. begingetresponse (<br/> New asynccallback (this. getresponsedone), <br/> req); <br/> // at this time, the system automatically transmits <br/> // IR as the parameter of getresponsedone, assign req to the asynstate member of IR. <Br/>}< br/> catch (exception e) <br/>{< br/> console. writeline (E. tostring (); <br/>}</P> <p >}< br/> // asynchronous call <br/> Public void getrequeststreamdone (object state) <br/> {<br/> console. writeline ("getrequeststreamdone:" + <br/> system. threading. thread. currentthread. managedthreadid. tostring (); <br/> iasyncresult IR = (iasyncresult) State; <br/> httpwebrequest Req = (httpwebrequest) IR. asyncstate; <br/> stream requeststream = req. endgetrequeststream (IR); </P> <p> streamwriter Sw = new streamwriter (requeststream, encoding. ASCII); <br/> SW. write (this. strformdata); // write form data (urlencoded) <br/> SW. close (); <br/> requeststream. close (); <br/> // send and obtain the server response <br/> req. begingetresponse (New asynccallback (this. getresponsedone), req); <br/>}< br/> // send a POST request <br/> Public void sendpostrequest () <br/>{< br/> try <br/> {<br/> httpwebrequest Req = (httpwebrequest) webrequest. create (struri); <br/> // build the header <br/> req. contenttype = "application/X-WWW-form-urlencoded"; <br/> req. contentlength = This. strformdata. length; <br/> req. method = "Post"; <br/> req. cookiecontainer = This. currentcookiecontainer; </P> <p> // construct the form data <br/> req. begingetrequeststream (this. getrequeststreamdone, req); </P> <p >}< br/> catch (exception e) <br/>{< br/> console. writeline (E. tostring (); <br/>}< br/>

In fact, APM is quite simple and intuitive to use. The procedure is as follows:

(1) Call httpwebrequest. beginxxx (asynccallback callback, object state)

This function initiates an asynchronous call and automatically uses the iasyncresult object that represents this asynchronous operation as the real parameter of the callback function. The State is assigned to the asyncstate Member of the iasyncresult object.

(2) Call httpwebrequest. endxxx (IR) in the callback function to read the response.

 

In the APM model, the callback function is automatically enabled by the CLR to execute a new thread after the waiting operation is completed.

Note that,Synchronous and asynchronous methods cannot be used together for the same httpwebrequest object, Begingetrequeststream () and begingetresponse () must be used at the same time. getrequeststream () and begingetresponse () cannot be used together. That is to say, a specific httpwebrequest object either executes asynchronous operations or synchronous operations, and cannot mix synchronous and asynchronous functions. In fact, the first called function prevails. If the synchronous function is called first, it will still be executed in synchronous mode even if the asynchronous function is called later.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.