Submitting a web form using C#

て烟熏妆下的殇ゞ 提交于 2019-12-13 06:01:13

问题


I have seen projects that are similar on stackexchange but not the same.

Question:

How can I submit this form correctly. (The code I have tried is below.)

I need to fill in the username and password fields and hit submit. When I tried submitted the form the webBrowser1.url should be redirected to another page. (Which its not) I know the URL will redirect properly because if I go to a page that I dont have permission to go to it redirects me back to this page.

    WebBrowser webBrowser1 = new WebBrowser();

    string URL_mainLoginScreen = @"192.168.2.10:8080/login.jsp";
    bool pageLoaded = false;

    public Form1()
    {
        InitializeComponent();
        webBrowser1.Navigating += new WebBrowserNavigatingEventHandler(webBrowser1_Navigating);
        webBrowser1.Navigated += new WebBrowserNavigatedEventHandler(webBrowser1_Navigated);
    }

    // Navigates to the given URL if it is valid.
    private void Navigate(String address)
    {
        if (String.IsNullOrEmpty(address)) return;
        if (address.Equals("about:blank")) return;
        if (!address.StartsWith("http://") &&
            !address.StartsWith("https://"))
        {
            address = "http://" + address;
        }
        try
        {
            webBrowser1.Navigate(new Uri(address));
        }
        catch (System.UriFormatException)
        {
            return;
        }
    }

    //Called while navigating (not ready)
    private void webBrowser1_Navigating(object sender,WebBrowserNavigatingEventArgs e)
    {
    }

    //Called after navigation (page ready to parse!)
    private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
    {
        pageLoaded = true;
    }

    private void button3_Click(object sender, EventArgs e)
    {
        Navigate(URL_mainLoginScreen);
        while (pageLoaded != true)
            Application.DoEvents();
        HtmlElement username = webBrowser1.Document.GetElementById("USERNAME");
        HtmlElement password = webBrowser1.Document.GetElementById("PASSWORD");
        HtmlElement submitForm = webBrowser1.Document.GetElementById("form1");
        if (username != null)
            username.SetAttribute("value", "user");
        if (password != null)
            password.SetAttribute("value", "password");
        if (submitForm != null)
            submitForm.InvokeMember("Click");

        Application.DoEvents();
    }

Webpage

https://www.dropbox.com/s/aijeslqtca7x0of/webpageExample.html

来源:https://stackoverflow.com/questions/20233057/submitting-a-web-form-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!