通過HttpWebRequest 發送 POST 請求實現自動登陸

怎樣通過HttpWebRequest 發送 POST 請求到一個網頁服務器?例如編寫個程序實現自動用戶登錄,自動提交表單數據到網站等。
假如某個頁面有個如下的表單(Form):

  1. <form name="form1" action="http:www.breakn.com/login.asp" method="post">   
  2. <input type="text" name="userid" value="">   
  3. <input type="password" name="password" value="">   
  4. </form>  

從表單可看到表單有兩個表單域,一個是userid另一個是password,所以以POST形式提交的數據應該包含有這兩項。
其中POST的數據格式爲:
表單域名稱1=值1&表單域名稱2=值2&表單域名稱3=值3……
要注意的是“值”必須是經過HTMLEncode的,即不能包含“<>=&”這些符號。

本例子要提交的數據應該是:
userid=value1&password=value2

用C#寫提交程序:

view plaincopy to clipboardprint?
  1. string strId = "guest";   
  2. string strPassword= "123456";   
  3.   
  4. ASCIIEncoding encoding=new ASCIIEncoding();   
  5. string postData="userid="+strId;   
  6. postData += ("&password="+strPassword);   
  7.   
  8. byte[] data = encoding.GetBytes(postData);   
  9.   
  10. // Prepare web request...   
  11. HttpWebRequest myRequest =   
  12. (HttpWebRequest)WebRequest.Create("http:www.here.com/login.asp");   
  13.   
  14. myRequest.Method = "POST";   
  15. myRequest.ContentType="application/x-www-form-urlencoded";   
  16. myRequest.ContentLength = data.Length;   
  17. Stream newStream=myRequest.GetRequestStream();   
  18.   
  19. // Send the data.   
  20. newStream.Write(data,0,data.Length);   
  21. newStream.Close();   
  22.   
  23. // Get response   
  24. HttpWebResponse myResponse=(HttpWebResponse)myRequest.GetResponse();   
  25. StreamReader reader = new StreamReader(response.GetResponseStream(),Encoding.Default);   
  26. string content = reader.ReadToEnd();   
  27. Console.WriteLine(content); 
發佈了50 篇原創文章 · 獲贊 1 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章