通过httpWebRequest发布数据

我需要使用来自我的应用程序(桌面)的HttpWebRequest对象将一些数据“发布”到外部网站,并通过HttpWebRequest对象将响应返回到我的应用程序。 但是,发布数据的网页上有带动态名称的文本框。

如何在HttpWebResquest获取这些文本框的名称并发布数据?

例如,当我加载页面的文本框的名字就是这样U2FsdGVkX183MTQyNzE0MrhLOmUpqd3eL60xF19RmCwLlSiG5nC1H6wvtBDhjI3uM1krX_B8Fwc但是当我刷新页面名称更改这个U2FsdGVkX182MjMwNjIzMPAtotst_q9PP9TETomXB453Mq3M3ZY5HQt70ZeyxbRb118Y8GQbgP8

谢谢你的任何建议。

 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"); } 

您可以通过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(); 

看起来您必须使用HttpWebRequest获取页面并解析相应HttpWebResponse的内容以找出文本框的名称。 然后使用另一个HttpWebRequest将值提交给页面。

基本上,您需要做的是以下内容:

  1. 使用GET方法向带有文本框的页面所在的URL发出HttpWebRequest
  2. 获取HttpWebResponse的响应流
  3. 解析响应流中包含的页面并获取文本框的名称。 您可以使用HTML Agility Pack来实现此目的。
  4. 使用POST方法发出HttpWebRequest,内容类型设置为“application / x-www-form-urlencoded”,键值对作为内容。

问题的第一部分:也许HTML树是稳定的。 然后,您可以通过XPath找到您的interrest文本框。 使用XmlReader,XDocument和Linq来完成它。

我用这个函数发布数据。 但是你传递的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