怎樣通過(guò)HttpWebRequest 發(fā)送 POST 請(qǐng)求到一個(gè)網(wǎng)頁(yè)服務(wù)器?例如編寫(xiě)個(gè)程序?qū)崿F(xiàn)自動(dòng)用戶登錄,自動(dòng)提交表單數(shù)據(jù)到網(wǎng)站等。
假如某個(gè)頁(yè)面有個(gè)如下的表單(Form):view plaincopy to clipboardPRint?
<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>
<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>從表單可看到表單有兩個(gè)表單域,一個(gè)是userid另一個(gè)是password,所以以POST形式提交的數(shù)據(jù)應(yīng)該包含有這兩項(xiàng)。
其中POST的數(shù)據(jù)格式為:
表單域名稱1=值1&表單域名稱2=值2&表單域名稱3=值3……
要注意的是“值”必須是經(jīng)過(guò)HTMLEncode的,即不能包含“<>=&”這些符號(hào)。
本例子要提交的數(shù)據(jù)應(yīng)該是:
userid=value1&password=value2
用C#寫(xiě)提交程序:view plaincopy to clipboardprint?
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);
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注