Transferred from: http://blog.csdn.net/pan_junbiao/article/details/9155497
C # uses GET, POST requests to get results, and here is an example of a simple user login.
1. Get results using GET request
1.1 Creating a Loginhandler.aspx Processing page
protected voidPage_Load (Objectsender, EventArgs e) { stringresult =""; stringUserName = request.querystring["UserName"]; stringPassword = request.querystring["Password"]; if(UserName = ="Admin"&& Password = ="123") {result="Landing Success"; } Else{result="Login Failed"; } response.write (Result);}
1.2 Write GET request and get result method
/// <summary>///GET request and get result/// </summary> Public Static stringHttpGet (stringUrlstringpostdatastr) {HttpWebRequest Request= (HttpWebRequest) webrequest.create (Url + (Postdatastr = =""?"":"?") +postdatastr); Request. Method="GET"; Request. ContentType="Text/html;charset=utf-8"; HttpWebResponse Response=(HttpWebResponse) request. GetResponse (); Stream Myresponsestream=Response. GetResponseStream (); StreamReader Mystreamreader=NewStreamReader (Myresponsestream, Encoding.UTF8); stringRetString =Mystreamreader.readtoend (); Mystreamreader.close (); Myresponsestream.close (); returnretstring;}
1.3 Calling Test
Static void Main (string[] args) { stringhttp://www.mystudy.cn/LoginHandler.aspx "; string " username=admin&password=123 " ; string result = httpget (URL, data); Console.WriteLine (result); Console.ReadLine ();}
2. Get results using POST request
2.1 Creating a loginhandler.aspx Processing page
protected voidPage_Load (Objectsender, EventArgs e) { stringresult =""; stringUserName = request.form["UserName"]; stringPassword = request.form["Password"]; if(UserName = ="Admin"&& Password = ="123") {result="Landing Success"; } Else{result="Login Failed"; } response.write (Result);}
2.2 Writing Post requests and getting results methods
/// <summary>///POST request and get results/// </summary> Public Static stringHttpPost (stringUrlstringpostdatastr) {HttpWebRequest Request=(HttpWebRequest) webrequest.create (URL); Request. Method="POST"; Request. ContentType="application/x-www-form-urlencoded"; Request. ContentLength=postdatastr.length; StreamWriter writer=NewStreamWriter (Request. GetRequestStream (), encoding.ascii); Writer. Write (POSTDATASTR); Writer. Flush (); HttpWebResponse Response=(HttpWebResponse) request. GetResponse (); stringencoding =Response. ContentEncoding; if(Encoding = =NULL|| Encoding. Length <1) {Encoding="UTF-8";//default Encoding} StreamReader Reader=NewStreamReader (response. GetResponseStream (), encoding.getencoding (Encoding)); stringRetString =Reader. ReadToEnd (); returnretstring;}
2.3 Calling Test
Static void Main (string[] args) { stringhttp://www.mystudy.cn/LoginHandler.aspx "; string " username=admin&password=123 " ; string result = httppost (URL, data); Console.WriteLine (result); Console.ReadLine ();}
C # uses GET, POST requests to get results