繁体   English   中英

从C#代码发布html表单

[英]Post html form from C# code

所以我想完全从代码发布到同一域内的表单。 我想我有我需要的一切,除了如何包含表格数据。 我需要包含的值来自隐藏字段和输入字段,让我们调用它们:

<input type="text" name="login" id="login"/>
<input type="password" name="p" id="p"/>
<input type = hidden name="a" id="a"/>

到目前为止我所拥有的是什么

WebRequest req = WebRequest.Create("http://www.blah.com/form.aspx")
req.ContentType = "application/x-www-form-urlencoded"
req.Method = "POST"

如何在请求中包含这三个输入字段的值?

NameValueCollection nv = new NameValueCollection();
nv.Add("login", "xxx");
nv.Add("p", "yyy");
nv.Add("a", "zzz");

WebClient wc = new WebClient();
byte[] ret = wc.UploadValues(""http://www.blah.com/form.aspx", nv);

如上面评论中提供的链接所示,如果您使用的是WebRequest而不是WebClient,可能要做的事情是构建一串由&分隔的键值对,并使用url编码的值:

  foreach(KeyValuePair<string, string> pair in items)
  {      
    StringBuilder postData = new StringBuilder();
    if (postData .Length!=0)
    {
       postData .Append("&");
    }
    postData .Append(pair.Key);
    postData .Append("=");
    postData .Append(System.Web.HttpUtility.UrlEncode(pair.Value));
  }

当您发送请求时,使用此字符串设置ContentLength并将其发送到RequestStream:

request.ContentLength = postData.Length;
using(Stream writeStream = request.GetRequestStream())
{
    UTF8Encoding encoding = new UTF8Encoding();
    byte[] bytes = encoding.GetBytes(postData);
    writeStream.Write(bytes, 0, bytes.Length);
}

您可以根据需要提取功能,因此无需将其拆分为多种方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM