WinForm Sending HTTP requests
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Net;usingSystem.Text;usingsystem.web;namespacedingtest.utility.tools{ Public classHttphelper {/// <summary> ///GET request Mode/// </summary> /// <param name= "urlstring" >the requested URL</param> /// <returns></returns> Public Static stringGet (stringurlstring) { //Defining local VariablesHttpWebRequest HttpWebRequest =NULL; HttpWebResponse Httpwebrespones=NULL; Stream Stream=NULL; stringHtmlstring =string. Empty; //Request Page Try{HttpWebRequest= WebRequest.Create (urlstring) asHttpWebRequest; } //Handling Exceptions Catch(Exception ex) {Throw NewException ("An error occurred while creating the page request! ", ex); } httpwebrequest.useragent="mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;. NET CLR 2.0.50727; Maxthon 2.0)"; //get the return information of the server Try{httpwebrespones=(HttpWebResponse) httpwebrequest.getresponse (); Stream=Httpwebrespones.getresponsestream (); } //Handling Exceptions Catch(Exception ex) {Throw NewException ("An error occurred while accepting the server's return page! ", ex); } StreamReader StreamReader=NewStreamReader (stream, Encoding.UTF8); //Read back Page Try{htmlstring=Streamreader.readtoend (); } //Handling Exceptions Catch(Exception ex) {Throw NewException ("An error occurred while reading the page data! ", ex); } //Releasing resources returns resultsStreamreader.close (); Stream. Close (); returnhtmlstring; } /// <summary> ///POST Request Mode/// </summary> /// <param name= "url" >the requested URL</param> /// <param name= "param" >The requested parameter JSON</param> /// <returns></returns> Public Static stringPost (stringUrlstringparam) { stringstrURL =URL; System.Net.HttpWebRequest request; Request=(System.Net.HttpWebRequest) webrequest.create (strURL); Request. Method="POST"; Request. ContentType="Application/json;charset=utf-8"; stringparaurlcoded =param; byte[] payload; Payload=System.Text.Encoding.UTF8.GetBytes (paraurlcoded); Request. ContentLength=payload. Length; Stream writer=request. GetRequestStream (); Writer. Write (Payload,0, payload. Length); Writer. Close (); System.Net.HttpWebResponse response; Response=(System.Net.HttpWebResponse) request. GetResponse (); System.IO.Stream s; S=Response. GetResponseStream (); stringStrdate =""; stringstrvalue =""; StreamReader Reader=NewStreamReader (S, Encoding.UTF8); while((strdate = Reader.readline ())! =NULL) {strvalue+ = Strdate +"\ r \ n"; } returnstrvalue; } }}
C # impersonate an HTTP request