怎樣通過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();
- Console.WriteLine(content);