【.Net基礎03】HttpWebRequest模擬瀏覽器登錄

【原理】web

【代碼】app

 1 private void button2_Click(object sender, EventArgs e)
 2         {
 3             string url =「請求的地址」 
 4             indata = 「傳入的數據&傳入的數據」;
 5             string outdata = "";
 6             byte[] data = System.Text.Encoding.UTF8.GetBytes(indata);
 7 
 8             //新建一個HttpWebRequest 
 9             HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
10 
11             //必定要設置ContentType
12             myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
13             myHttpWebRequest.ContentLength = data.Length;
14             myHttpWebRequest.Method = "POST";
15 
16             //新建一個CookieContainer來存放Cookie集合 
17             CookieContainer myCookieContainer = new CookieContainer();
18 
19             //設置HttpWebRequest的CookieContainer爲剛纔創建的那個myCookieContainer 
20             myHttpWebRequest.CookieContainer = myCookieContainer;
21 
22             //把數據寫入HttpWebRequest的Request流 
23             Stream myRequestStream = myHttpWebRequest.GetRequestStream();
24             myRequestStream.Write(data, 0, data.Length);
25             StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8"));
26 
27             //關閉打開對象 
28             myRequestStream.Flush();
29             myRequestStream.Close();
30 
31             //新建一個HttpWebResponse 
32             HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
33 
34             //把數據從HttpWebResponse的Response流中讀出 
35             Stream myResponseStream = myHttpWebResponse.GetResponseStream();
36             StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
37             outdata = myStreamReader.ReadToEnd();
38 
39             //關閉打開的對象 
40             myStreamReader.Close();
41             myResponseStream.Close();
42 
43             //顯示"登陸" 
44             //拿到了Cookie,再進行請求就能直接讀取到登陸後的內容了 
45             myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
46 
47             //剛纔那個CookieContainer已經存有了Cookie,把它附加到HttpWebRequest中則能直接經過驗證 
48             myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
49 
50             //讀取登錄後的內容
51             myResponseStream = myHttpWebResponse.GetResponseStream();
52             myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
53             outdata = myStreamReader.ReadToEnd();
54 
55             //關閉打開的對象 
56             myStreamReader.Close();
57             myResponseStream.Close();
58 
59             Console.WriteLine(outdata);
60             this.webBrowser1.DocumentText = outdata;
61         }
View Code

 

【備註】ide

當Cookie被設置爲HttpOnly時,此方法就沒法獲取Cookie了,關於HttpOnly的限制,下一篇文章將繼續研究。this

相關文章
相關標籤/搜索