C#實現通過HttpWebRequest發送POST請求實現

C#實現通過HttpWebRequest發送POST請求實現網站自動登陸

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

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

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

用C#寫提交程序:
string strId = “guest”;
string strPassword= “123456”;

ASCIIEncoding encoding=new ASCIIEncoding();
string postData=“userid=”+strId;
postData += ("&password="+strPassword);

byte[] data = encoding.GetBytes(postData);

// Prepare web request
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create(“http://www.sina.com/login.asp”);

myRequest.Method = “POST”;
myRequest.ContentType=“application/x-www-form-urlencoded”;
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();

// Send the data.
newStream.Write(data,0,data.Length);
newStream.Close();

// Get response
HttpWebResponse myResponse=(HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(),Encoding.Default);
string content = reader.ReadToEnd();
Response.Write(content);

此方法核心問題是要找到請求頁和表單域中的參數ID。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章