2

我正在编写一个简单的 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 中(复选框、文本等)

4

1 回答 1

11

就我个人而言,我要做的是将参数构建为 aDictionary<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();
于 2012-11-19T10:38:37.943 回答