2010-03-31 18 views
13

我需要「郵報」的一些數據使用 HttpWebRequest對象從我的應用程序(桌面)外部網站,並通過HttpWebResponse對象得到響應 回到我的應用程序。 但是我在其上發佈數據的網頁上有具有動態名稱的文本框。後數據

如何獲取這些文本框的名稱並在HttpWebResquest中發佈數據?

例如,當我加載頁面的文本框名稱是這樣的U2FsdGVkX183MTQyNzE0MrhLOmUpqd3eL60xF19RmCwLlSiG5nC1H6wvtBDhjI3uM1krX_B8Fwc,但當我刷新頁面名稱更改爲這個U2FsdGVkX182MjMwNjIzMPAtotst_q9PP9TETomXB453Mq3M3ZY5HQt70ZeyxbRb118Y8GQbgP8

感謝您的任何建議。

回答

9

您可以通過XPath例如:和用戶他們喜歡:

byte[] data = new ASCIIEncoding().GetBytes("textBoxName1=blabla"); 
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/myservlet"); 
httpWebRequest.Method = "POST"; 
httpWebRequest.ContentType = "application/x-www-form-urlencoded"; 
httpWebRequest.ContentLength = data.Length; 
Stream myStream = httpWebRequest.GetRequestStream(); 
myStream.Write(data,0,data.Length); 
myStream.Close(); 
30
var request = WebRequest.Create("http://foo"); 
request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded"; 
using (var writer = new StreamWriter(request.GetRequestStream())) 
{ 
    writer.Write("field=value"); 
} 
+0

但我不知道提前的字段名稱。 多數民衆贊成在這個問題? 字段名稱不會硬編碼,只要頁面加載或刷新,字段名稱都會更改。 – user304901 2010-03-31 07:14:13

+1

另外一個問題是,因爲它在這個問題上完全是偏離主題(並不意味着它通常是SO) – jalgames 2014-04-08 19:22:04

2

看起來你將有一個HttpWebRequest的下載頁面,並解析的內容對應的HttpWebResponse找出的文本框的名稱。然後通過使用另一個HttpWebRequest將值提交給頁面。

因此,基本上,你需要做的是以下幾點:

  1. 問題一個HttpWebRequest的使用GET方法,其中使用文本框的頁面位於
  2. 獲取的響應流的URL HttpWebResponse
  3. 解析響應流中包含的頁面並獲取文本框的名稱。您可以使用HTML Agility Pack來達到此目的。
  4. 使用POST方法發出HttpWebRequest,內容類型設置爲「application/x-www-form-urlencoded」和鍵值對作爲內容。
0

我用這個函數發佈數據。但是你通過URL已被格式化爲例如例如

http://example.com/login.php?userid=myid&password=somepassword

Private Function GetHtmlFromUrl(ByVal url As String) As String 

     If url.ToString() = vbNullString Then 
      Throw New ArgumentNullException("url", "Parameter is null or empty") 
     End If 
     Dim html As String = vbNullString 
     Dim request As HttpWebRequest = WebRequest.Create(url) 
     request.ContentType = "Content-Type: application/x-www-form-urlencoded" 
     request.Method = "POST" 


     Try 
      Dim response As HttpWebResponse = request.GetResponse() 
      Dim reader As StreamReader = New StreamReader(response.GetResponseStream()) 
      html = Trim$(reader.ReadToEnd) 
      GetHtmlFromUrl = html 
     Catch ex As WebException 
      GetHtmlFromUrl = ex.Message 
     End Try 

    End Function 
0

你的問題的第一部分: 也許HTML樹是穩定的。然後,您可以通過XPath找到您的Interrest文本框。 使用XmlReader,XDocument和Linq來完成它。