HttpWebRequest模擬登陸,存儲Cookie以便登錄請求后使用


[一籃飯特稀原創,轉載請注明出自http://www.cnblogs.com/wanghafan/p/3284481.html]

PostLogin :登錄,並保存Cookie

復制代碼
 1  public static string PostLogin(string postData, string requestUrlString, ref CookieContainer cookie)
 2     {
 3         ASCIIEncoding encoding = new ASCIIEncoding();
 4         byte[] data = encoding.GetBytes(postData);
 5         //向服務端請求
 6         HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(requestUrlString);
 7         myRequest.Method = "POST";
 8         myRequest.ContentType = "application/x-www-form-urlencoded";
 9         myRequest.ContentLength = data.Length;
10         myRequest.CookieContainer = new CookieContainer(); 11         Stream newStream = myRequest.GetRequestStream();
12         newStream.Write(data, 0, data.Length);
13         newStream.Close();
14         //將請求的結果發送給客戶端(界面、應用)
15         HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
16         cookie.Add(myResponse.Cookies);
17         StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
18         return reader.ReadToEnd();
19     }
復制代碼

PostRequest :登錄后使用Cookie進行其他操作

復制代碼
 1  public static string PostRequest(string postData, string requestUrlString, CookieContainer cookie)
 2     {
 3         ASCIIEncoding encoding = new ASCIIEncoding();
 4         byte[] data = encoding.GetBytes(postData);
 5         HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(requestUrlString);
 6         myRequest.Method = "POST";
 7         myRequest.ContentType = "application/x-www-form-urlencoded";        
 8         myRequest.ContentLength = data.Length;
 9         myRequest.CookieContainer = cookie; 10         Stream newStream = myRequest.GetRequestStream();
11         newStream.Write(data, 0, data.Length);
12         newStream.Close();
13         HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
14         StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
15         return reader.ReadToEnd();
16     }
復制代碼

e.g.

復制代碼
1             string strIMSPhone = tb_IMSPhone.Text.Trim();
2             string strIMSPwd = tb_IMSPwd.Text.Trim();
3             string postData = "username=" + strIMSPhone + "&password=" + strIMSPwd + "&type=2";
4             CookieContainer cookie=new CookieContainer();
5             if (IMSHelper.PostLogin(postData, post_signIn, ref cookie).Equals("ok"))
6             {
7                 string strCont = PostRequest("", post_getContJsonData, cookie);    
8             }
復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM