我正在寫一個簡單的C#程序來做一些Web請求和發佈數據。 我瞭解基本知識如何使用密碼和html表單的東西登錄。 但是我想知道是否有很多輸入參數(如這個問題頁面)像複選框和文本字段,是否有任何有效的方法比硬編碼字符串中的20個參數並將其傳入?我可以讀取html文件解析它,並掃描輸入並使用String builder來製作這樣的字符串,但我想知道是否有比這更有效的方法?C#HttpWebRequest Post方法很多參數的形式
private HtmlAgilityPack.HtmlDocument getpage(string url ,String input)
{
try
{
Stream datastream;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
request.AllowAutoRedirect = true;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
request.ContentType = "application/x-www-form-urlencoded";
if (input!=null)
{
String postData = "";
request.Method = "POST";
if (input == "login")
{
postData = String.Format("username={0}&password={1}", "myusername", "mypassword");
}
else if (input == "sendMessage")
{
//THIS IS THE LONG STRING THAT I DON'T WANT TO HARD CODE
postData = String.Format("reciever={0}&sendmessage={1}", "thepersontomessage" ,this.DefaultMessage);
//I am just puting two parameters for now, there should be alot
}
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
datastream = request.GetRequestStream();
datastream.Write(byteArray, 0, byteArray.Length);
datastream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
datastream = response.GetResponseStream();
String sourceCode = "";
using (StreamReader reader = new StreamReader(datastream))
{
sourceCode = reader.ReadToEnd();
}
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.LoadHtml(sourceCode);
this.cookies.Add(response.Cookies);
return htmlDoc;
}
catch (Exception)
{
return null;
}
也有一個簡單的方法,看看有什麼是設置爲當我點擊瀏覽器(基本帖子的網址字符串和發送參數值)範圍內的HTML窗體上按鈕的參數值,這樣我就可以硬編碼這些值到Postdatastring(檢查boxs,文本等)
要看看有什麼布勞爾發送到服務器上,安裝[提琴手(http://fiddler2.com) – Alex