我正在编写一个简单的 C# 程序来执行一些 Web 请求和发布数据。 我了解基础知识的工作原理,例如如何使用密码和 html 表单的内容登录。 但是我想知道是否有很多输入参数(例如这个问题页面),比如复选框和文本字段,有没有比将20个参数硬编码在一个字符串中并传递进去更有效的方法?我可以读取 html 文件对其进行解析并扫描出输入并使用 String builder 来生成这样的字符串,但我想知道是否有比这样做更有效的方法?
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 表单上的按钮时设置的参数值(基本上是发送的 post url 字符串和参数值),因此我可以将这些值硬编码到Postdatastring(复选框、文本等)
最佳答案
就我个人而言,我会做的是将参数构建为 Dictionary<string,string>
这样你就可以做到:
var parms = new Dictionary<string,string>();
parms.Add("username","fred");
然后你可以有一个方法,例如:
string DictToString(Dictionary<string,string> dict)
{
StringBuilder builder = new StringBuilder();
foreach(KeyValuePair<string,string> kvp in dict) {
builder.Append(kvp.Key + "=" + kvp.Value + "&");
}
return builder.ToString();
}
然后您可以通过以下方式获取最终参数字符串:
var parms_str = builder.ToString();
关于C# HttpWebRequest Post 方法表单中的许多参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13451964/