提交页面,检查提交的字段名称,检查响应

时间:2011-11-05 11:23:56

标签: c# vb.net

我需要从Web应用程序获取数据。我无权访问数据库或应用程序源(.net)。

网络应用程序的工作方式如下 - 在字段中输入值,单击“提交”按钮,并在模式弹出窗口中返回与这些字段关联的数据。

我需要以编程方式执行相同的操作,而不是实际打开浏览器。

我需要知道需要发布的字段的名称和URL。然后存储响应。

任何.Net语言都可以。

有任何线索可以做到吗?感谢。

1 个答案:

答案 0 :(得分:0)

我使用这些功能发布页面并获得结果:

public static string HttpPost(string url, object[] postData, string saveTo = "")
{
    StringBuilder post = new StringBuilder();
    for (int i = 0; i < postData.Length; i += 2)
        post.Append(string.Format("{0}{1}={2}", i == 0 ? "" : "&", postData[i], postData[i + 1]));
    return HttpPost(url, post.ToString(), saveTo);
}
public static string HttpPost(string url, string postData, string saveTo = "")
{
    postData = postData.Replace("\r\n", "");
    try
    {
        WebRequest req = WebRequest.Create(url);
        byte[] send = Encoding.Default.GetBytes(postData);
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        //req.ContentType = "text/xml;charset=\"utf-8\"";
        req.ContentLength = send.Length;

        Stream sout = req.GetRequestStream();
        sout.Write(send, 0, send.Length);
        sout.Flush();
        sout.Close();

        WebResponse res = req.GetResponse();
        StreamReader sr = new StreamReader(res.GetResponseStream());
        string returnvalue = sr.ReadToEnd();
        if (!string.IsNullOrEmpty(saveTo))
            File.WriteAllText(saveTo, returnvalue);

        //Debug.WriteLine("{0}\n{1}", postData, returnvalue);
        return returnvalue;
    }
    catch (Exception ex)
    {
        Debug.WriteLine("POST Error on {0}\n  {1}", url, ex.Message);
        return "";
    }
}