【问题标题】:webBrowser Cookies and Form SubmittingwebBrowser Cookies 和表单提交
【发布时间】:2012-02-15 07:27:19
【问题描述】:

我想使用预定义的 cookie 导航到网站, 在input type="text" 中添加一些文本,然后使用提交按钮提交表单。 我知道可以做到,但我不知道怎么做。

我已经尝试将 POST 数据发送到页面,但我必须单击按钮才能执行操作。 这是我的代码:

        static String readHtmlPage(string url)
        {

        //setup some variables

        String username = "demo";
        String password = "password";
        String firstname = "John";
        String lastname = "Smith";

        //setup some variables end

        String result = "";
        String strPost = "username=" + username + "&password=" + password + "&firstname=" + firstname + "&lastname=" + lastname;
        StreamWriter myWriter = null;

        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
        objRequest.Headers["Cookie"] = "sid=0";
        objRequest.Headers["Cookie"] = "username=0";
        objRequest.Method = "POST";
        objRequest.ContentLength = strPost.Length;
        objRequest.ContentType = "application/x-www-form-urlencoded";

        try
        {
            myWriter = new StreamWriter(objRequest.GetRequestStream());
            myWriter.Write(strPost);
        }
        catch (Exception e)
        {
            return e.Message;
        }
        finally
        {
            myWriter.Close();
        }

        HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
        using (StreamReader sr =
           new StreamReader(objResponse.GetResponseStream()))
        {
            result = sr.ReadToEnd();

            // Close and clean up the StreamReader
            sr.Close();
        }
        return result;
    }


    static void Main(string[] args)
    {

        Console.Write(readHtmlPage("http://www.ggogle.com/"));
    }

【问题讨论】:

    标签: c# forms cookies browser


    【解决方案1】:

    我过去做过的建议是:
    - 使用 Fiddler 并使用浏览器访问该站点,然后像往常一样填写表格。
    - Fiddler 将记录请求/响应,您可以复制发布数据字符串并替换您需要的任何值,并使用 HttpWebRequest/HttpWebResponse 以编程方式执行 POST 并获取响应。

    post data through httpWebRequest

    示例:这是我提交最后一条评论时捕获的帖子数据。

    comment=When+you+collect+the+recorded+POST+string+you+can+swap+out+the+key+value+pairs+in+there+before+you+make+the+request.+When+the+OnClick+event+fires+it+will+POST+data+to+the+server%2C+this+is+what+you+need+to+recreate+nothing+with+the+javascript.&fkey=62a7d57a52ee7fa723413a2e1dbe7e71

    string postData = string.format("comment={0}&fkey={1}", myCommentString, myFKey);
    

    然后,您可以将此字符串传递给 POST 所针对的 url,并使用 HttpWebRequest 重新创建它。

    您还需要确保您在帖子字符串中对您的值进行 URL 编码。

    【讨论】:

    • 我每次都需要发送不同的值。如果我发送 POST 数据它不起作用,因为该操作绑定到提交按钮的 OnClick 事件。
    • 当您收集记录的 POST 字符串时,您可以在发出请求之前交换其中的键值对。当 OnClick 事件触发时,它会将数据 POST 到服务器,这就是你需要用 javascript 重新创建什么。
    • :D 随时,很高兴它有帮助
    猜你喜欢
    • 1970-01-01
    • 2011-01-18
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    相关资源
    最近更新 更多