C#HttpWebRequest Post Method表格中有很多参数

时间:2012-11-19 10:32:01

标签: c# .net html parameters httpwebrequest

我正在编写一个简单的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表单上的按钮时设置的参数值是什么(基本上是发送的url字符串和参数值)所以我可以将这些值硬编码到Postdatastring(复选框,文本等)

1 个答案:

答案 0 :(得分:11)

我个人会做的是将参数构建为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();