模擬登錄的原理很簡單,就是發送一個Http 請求服務器得到響應,而後客戶端獲取到cookie便可實現模擬登錄,好比一些搶票軟件的原理無非也是這樣模擬客戶端的cookie 而後發送請求去搶票。 本文將演示如何用C# 來實現模擬登錄的,推薦一款工具Fiddler,這是一款監聽http 請求的利器。廢話很少說,我就以博客園爲例來實現模擬登錄。首先我登錄博客園 http://passport.cnblogs.com/login.aspx 輸入用戶名和密碼點登錄 就會看到Fiddler 上的相關信息:html
Ok,我首先須要發送一個http 請求 ,這個請求時POST的方式,而後用戶名和密碼就是POST的數據。代碼以下:服務器
1 static CookieContainer GetCookie(string postString, string postUrl) 2 { 3 4 CookieContainer cookie = new CookieContainer(); 5 6 HttpWebRequest httpRequset = (HttpWebRequest)HttpWebRequest.Create(postUrl);//建立http 請求 7 httpRequset.CookieContainer = cookie;//設置cookie 8 httpRequset.Method = "POST";//POST 提交 9 httpRequset.KeepAlive = true; 10 httpRequset.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"; 11 httpRequset.Accept = "text/html, application/xhtml+xml, */*"; 12 httpRequset.ContentType = "application/x-www-form-urlencoded";//以上信息在監聽請求的時候都有的直接複製過來 13 byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postString); 14 httpRequset.ContentLength = bytes.Length; 15 Stream stream = httpRequset.GetRequestStream(); 16 stream.Write(bytes, 0, bytes.Length); 17 stream.Close();//以上是POST數據的寫入 18 19 HttpWebResponse httpResponse = (HttpWebResponse)httpRequset.GetResponse();//得到 服務端響應 20 return cookie;//拿到cookie 21 }
拿到cookie 以後咱們就能夠以用戶的什麼去用戶的後臺或者其餘的地方:cookie
1 static string GetContent(CookieContainer cookie, string url) 2 { 3 string content; 4 HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url); 5 httpRequest.CookieContainer = cookie; 6 httpRequest.Referer = url; 7 httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"; 8 httpRequest.Accept = "text/html, application/xhtml+xml, */*"; 9 httpRequest.ContentType = "application/x-www-form-urlencoded"; 10 httpRequest.Method = "GET"; 11 12 HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse(); 13 14 using (Stream responsestream = httpResponse.GetResponseStream()) 15 { 16 17 using (StreamReader sr = new StreamReader(responsestream, System.Text.Encoding.UTF8)) 18 { 19 content = sr.ReadToEnd(); 20 } 21 } 22 23 return content; 24 }
OK 下面是調用 我寫的是一個控制檯程序:app
1 1 static void Main(string[] args) 2 2 { 3 3 string loginstr = "{要post 的登錄數據包括用戶名和密碼}"; 4 4 5 5 //從登錄的地址獲取cookie 6 6 CookieContainer cookie = GetCookie(loginstr, "http://passport.cnblogs.com/login.aspx"); 7 7 8 8 //這個是進入後臺地址 9 9 Console.WriteLine(GetContent(cookie, "http://i.cnblogs.com/EditPosts.aspx")); 10 10 11 11 Console.Read(); 12 12 }
能夠看到我已經進入了後臺了:ide
若是我是沒有登錄的狀況下進入這個地址是這樣的:工具
下次我就寫一下怎麼在模擬登錄以後發送http 請求實現添加刪除這些效果。post