私は単純な C# プログラムを作成して、Web リクエストとデータの投稿を行います。パスワードでログインする方法やhtmlフォームのような基本がどのように機能するかを理解しています。しかし、チェックボックスやテキストフィールドのような多くの入力パラメーター (この質問ページなど) があるかどうか疑問に思っています.20個のパラメーターを文字列にハードコーディングして渡すよりも効率的な方法はありますか? HTMLファイルを読み込んで解析し、入力をスキャンしてStringビルダーを使用してそのような文字列を作成できますが、それよりも効率的な方法があるのでしょうか?
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 フォームのボタンをクリックしたときにパラメーター値がどのように設定されているかを確認する簡単な方法 (基本的には、送信される投稿 URL 文字列とパラメーター値) があるので、それらの値を Postdatastring にハードコーディングできます (チェックボックス、テキストなど)