2013-01-12 37 views
1

因此,我想完全從代碼發佈到同一個域內的表單。除了如何包含表單數據之外,我想我擁有我需要的一切。我需要包括的值是從隱藏字段和輸入字段,我們姑且稱之爲:從C#發佈html表單代碼

<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" 

怎樣包括在這三個輸入字段的值請求?

+0

這個問題的答案之一:http://stackoverflow.com/questions/2962155/c-sharp-web-request-with-post-encoding-question建議看看這個網頁:http:// geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx我認爲正是你需要的。最相關的部分是代碼末尾的EncodeAndAddItem()方法以及如何使用該方法。 – JLRishe

+0

[.net後表單在代碼後面]的可能重複(http://stackoverflow.com/questions/11394229/net-post-form-in-code-behind) –

+1

我認爲我的情況與那個稍有不同。我不想在代碼中重新生成表單值。 – user609926

回答

3
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); 
0

正如在我的評論提供上面,如果你使用的是WebRequest的,而不是一個Web客戶端的鏈接顯示,可能是我們該做的是建立由&分隔的鍵值對的字符串,用值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); 
} 

您可能能夠根據您的需求提取功能,因此無需將其分解爲多種方法。