C# HTTP Request請求程序模擬是如何實(shí)現(xiàn)的呢?我們在實(shí)現(xiàn)發(fā)送請求的操作是會(huì)用到哪些方法呢?那么下面我們來看看具體的實(shí)現(xiàn)方法,使用下面的代碼片段時(shí),記得 在程序的引用上右鍵,然后添加引用,添加 System.Web. 就可以使用下面的代碼了.
C# HTTP Request請求程序模擬實(shí)例
- using System.Net;
- using System.IO;
- using System.Web;
- /********************
- *C# HTTP Request請求程序模擬***
- * 向服務(wù)器送出請求
- * */
- public string SendRequest(string param)
- {
- ASCIIEncoding encoding = new ASCIIEncoding();
- byte[] data = encoding.GetBytes(param);
- HttpWebRequest request =
- (HttpWebRequest)HttpWebRequest.Create(this.url);
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded";
- request.ContentLength = data.Length;
- Stream sm = request.GetRequestStream();
- sm.Write(data, 0, data.Length);
- sm.Close();
- HttpWebResponse response =
- (HttpWebResponse)request.GetResponse();
- if (response.StatusCode.ToString() != "OK")
- {
- MessageBox.Show(response.StatusDescription.ToString());
- return "";
- }
- StreamReader myreader = new StreamReader(
- response.GetResponseStream(), Encoding.UTF8);
- string responseText = myreader.ReadToEnd();
- return responseText;
- }
- /**C# HTTP Request請求程序模擬
- * 進(jìn)行UTF-8的URL編碼轉(zhuǎn)換(針對漢字參數(shù))
- * */
- public string EncodeConver(string instring)
- {
- return HttpUtility.UrlEncode(instring, Encoding.UTF8);
- }
- /**C# HTTP Request請求程序模擬
- * 進(jìn)行登錄操作并返回相應(yīng)結(jié)果
- * */
- public bool DoLogin(string username,
- string password)
- {
- password = System.Web.Security.FormsAuthentication.
- HashPasswordForStoringInConfigFile(password, "MD5");
- string param = string.Format("do=login&u={0}&p={1}",
- this.EncodeConver(username), this.EncodeConver(password));
- string result = this.SendRequest(param);
- // MessageBox.Show(result); 解析 Result ,我這里是作為一個(gè)XML Document來解析的
- return true;
- }
C# HTTP Request請求程序模擬的基本內(nèi)容就向你介紹到這里,希望對你了解和學(xué)習(xí)C# HTTP Request請求程序模擬有所幫助。