C#使用GET、POST请求获取结果
C#使用GET、POST请求获取结果,这里以一个简单的用户登陆为例。
1、使用GET请求获取结果
1.1创建LoginHandler.aspx处理页面
protectedvoidPage_Load(objectsender,EventArgse) { stringresult=""; stringuserName=Request.QueryString["UserName"]; stringpassword=Request.QueryString["Password"]; if(userName=="admin"&&password=="123") { result="登陆成功"; } else { result="登陆失败"; } Response.Write(result); }
1.2编写GET请求与获取结果方法
///<summary> ///GET请求与获取结果 ///</summary> publicstaticstringHttpGet(stringUrl,stringpostDataStr) { HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(Url+(postDataStr==""?"":"?")+postDataStr); request.Method="GET"; request.ContentType="text/html;charset=UTF-8"; HttpWebResponseresponse=(HttpWebResponse)request.GetResponse(); StreammyResponseStream=response.GetResponseStream(); StreamReadermyStreamReader=newStreamReader(myResponseStream,Encoding.UTF8); stringretString=myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); returnretString; }
1.3调用测试
staticvoidMain(string[]args) { stringurl="http://www.mystudy.cn/LoginHandler.aspx"; stringdata="UserName=admin&Password=123"; stringresult=HttpGet(url,data); Console.WriteLine(result); Console.ReadLine(); }
2、使用POST请求获取结果
2.1创建LoginHandler.aspx处理页面
protectedvoidPage_Load(objectsender,EventArgse) { stringresult=""; stringuserName=Request.Form["UserName"]; stringpassword=Request.Form["Password"]; if(userName=="admin"&&password=="123") { result="登陆成功"; } else { result="登陆失败"; } Response.Write(result); }
2.2编写POST请求与获取结果方法
///<summary> ///POST请求与获取结果 ///</summary> publicstaticstringHttpPost(stringUrl,stringpostDataStr) { HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(Url); request.Method="POST"; request.ContentType="application/x-www-form-urlencoded"; request.ContentLength=postDataStr.Length; StreamWriterwriter=newStreamWriter(request.GetRequestStream(),Encoding.ASCII); writer.Write(postDataStr); writer.Flush(); HttpWebResponseresponse=(HttpWebResponse)request.GetResponse(); stringencoding=response.ContentEncoding; if(encoding==null||encoding.Length<1){ encoding="UTF-8";//默认编码 } StreamReaderreader=newStreamReader(response.GetResponseStream(),Encoding.GetEncoding(encoding)); stringretString=reader.ReadToEnd(); returnretString; }
2.3调用测试
staticvoidMain(string[]args) { stringurl="http://www.mystudy.cn/LoginHandler.aspx"; stringdata="UserName=admin&Password=123"; stringresult=HttpPost(url,data); Console.WriteLine(result); Console.ReadLine(); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。