#regionBackground emulation Browser Get/post request/// <summary> ///How to send a request/// </summary> /// <param name= "url" >Request URL</param> /// <param name= "Para" >Request Parameters</param> /// <param name= "method" >Request Method Get/post</param> /// <returns></returns> Public Static stringSendRequest (stringUrlstringParastringmethod) { stringStrresult =""; if(url = =NULL|| URL = ="") return NULL; if(Method = =NULL|| method = ="") Method="GET";
//Get mode if(method. ToUpper () = ="GET") { Try{System.Net.WebRequest WRQ= System.Net.WebRequest.Create (URL +para); Wrq. Method="GET"; Servicepointmanager.securityprotocol=SECURITYPROTOCOLTYPE.SSL3; System.Net.WebResponse WRP=WRQ. GetResponse (); System.IO.StreamReader SR=NewSystem.IO.StreamReader (WRP. GetResponseStream (), System.Text.Encoding.GetEncoding ("Utf-8")); Strresult=Sr. ReadToEnd (); } Catch(Exception ex) {returnEx. Message; } }
//Post Mode if(method. ToUpper () = ="POST") { if(para. Length >0&& para. IndexOf ('?') ==0) {para= para. Substring (1); } WebRequest req=webrequest.create (URL); Req. Method="POST"; Req. ContentType="application/x-www-form-urlencoded"; Servicepointmanager.securityprotocol=SECURITYPROTOCOLTYPE.SSL3; StringBuilder urlencoded=NewStringBuilder (); char[] Reserved= {'?','=','&' }; byte[] Somebytes =NULL; if(Para! =NULL) { inti =0, J; while(I <para. Length) {J=para. IndexOfAny (reserved, i); if(j = =-1) {urlencoded.append (Httputility.urlencode (para. Substring (I, para. Length-i), System.Text.Encoding.GetEncoding ("Utf-8"))); Break; } urlencoded.append (Httputility.urlencode (para. Substring (i, J-i), System.Text.Encoding.GetEncoding ("UTF-8"))); Urlencoded.append (para. Substring (J,1)); I= j +1; } somebytes=Encoding.Default.GetBytes (urlencoded.tostring ()); Req. ContentLength=somebytes.length; Stream Newstream=req. GetRequestStream (); Newstream.write (Somebytes,0, somebytes.length); Newstream.close (); } Else{req. ContentLength=0; } Try{WebResponse result=req. GetResponse (); Stream Receivestream=result. GetResponseStream (); Byte[] Read=Newbyte[ +]; intbytes = Receivestream.read (Read,0, +); while(Bytes >0) {//If the content is in ANSI code page format//Encoding encode = System.Text.Encoding.GetEncoding ("Shift-jis");Encoding encode = System.Text.Encoding.GetEncoding ("Utf-8"); Strresult+ = encode. GetString (Read,0, bytes); Bytes= Receivestream.read (Read,0, +); } returnstrresult; } Catch(Exception ex) {returnEx. Message; } } returnstrresult; } #endregion
Public Static stringSendRequest (stringUrlstringpara) { returnSendRequest (URL, para,"GET"); }
. NET background emulation browser Get/post request