所以我想从代码发布到同一域内的表单。我想我有我需要的一切,除了如何包括表单数据。我需要包含的值来自隐藏字段和输入字段,我们称它们为:
<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);
}
你可以根据你的需要提取功能,这样它就不需要被分割成那么多的方法。