通过httpWebRequest发送数据

13

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

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

例如,当我加载页面时,文本框名称为U2FsdGVkX183MTQyNzE0MrhLOmUpqd3eL60xF19RmCwLlSiG5nC1H6wvtBDhjI3uM1krX_B8Fwc,但是当我刷新页面时,名称更改为U2FsdGVkX182MjMwNjIzMPAtotst_q9PP9TETomXB453Mq3M3ZY5HQt70ZeyxbRb118Y8GQbgP8

感谢任何建议。

5个回答

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

但我事先不知道字段名是什么。 这是问题吗?? 字段名没有硬编码,它们会在每次页面加载或刷新时更改。 - user304901
1
请为此开设另一个问题,因为它完全不属于此问题的范畴(这并不意味着它在SO上是离题的)。 - jalgames

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();

2
看起来您需要使用 HttpWebRequest 获取页面并解析相应的 HttpWebResponse 的内容,以查找文本框的名称。然后,您可以使用另一个 HttpWebRequest 提交值到页面。
因此,基本上您需要做以下几件事情:
1. 使用 GET 方法向包含文本框页面的 URL 发出 HttpWebRequest 请求。 2. 获取 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找到你感兴趣的文本框。 使用XmlReader、XDocument和Linq来遍历它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接