[英]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.