C# HttpWebRequest Post 方法表单中的很多参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13451964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:36:29  来源:igfitidea点击:

C# HttpWebRequest Post Method many parameters in form

c#.nethtmlparametershttpwebrequest

提问by noobiehacker

I am writing a simple C# program to do some web request and posting data. I understand how the basics work like how to login with password and stuff of a html form. However I am wondering if there is a lot of input parameters (such as this question page ) like check boxes and text fields, is there any efficient method than hard-coding 20 parameters in a string and passing it in? I can read the html file parse it and scan out the input and use String builder to make such a string but I am wondering is there a more efficient method than doing that?

我正在编写一个简单的 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;
        }

Also is there a simple way to see what are the parameter values set to when I click a button on a html form within a browser (basically the post url string and parameter values that is sent) so I can hardcode those values into the Postdatastring (check boxs, texts etc)

还有一种简单的方法可以查看当我在浏览器中单击 html 表单上的按钮时设置的参数值是什么(基本上是发送的 url 字符串和参数值),以便我可以将这些值硬编码到 Postdatastring (复选框、文本等)

回答by Lloyd

Personally what I would do is build the parameters as a Dictionary<string,string>so that you can just do:

就我个人而言,我会做的是将参数构建为 aDictionary<string,string>以便您可以执行以下操作:

var parms = new Dictionary<string,string>();

parms.Add("username","fred");

You can then have a method such as:

然后你可以有一个方法,例如:

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();
}

You can then get the final parameter string with:

然后,您可以使用以下命令获取最终参数字符串:

var parms_str = builder.ToString();