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); 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.