C#實現通過HttpWebRequest發送POST請求實現網站自動登陸
來源:互聯網
上載者:User
怎樣通過HttpWebRequest 發送 POST 請求到一個網頁伺服器?例如編寫個程式實現自動使用者登入,自動認可表單資料到網站等。
假如某個頁面有個如下的表單(Form):
<form name="form1" action="http://www.breakn.com/login.asp" method="post">
<input type="text" name="userid" value="">
<input type="password" name="password" value="">
</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.here.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);