1

我想通过java填写一个HTTP表单的文本字段,然后想通过java点击提交按钮,以获取提交表单后返回的文档的页面源。我可以通过直接发送 HTTP 请求来做到这一点,但我不这样做。

4

3 回答 3

8

我通常使用HtmlUnit来做。他们的页面上有一个示例:

@Test
public void submittingForm() throws Exception {
    final WebClient webClient = new WebClient();

    // Get the first page
    final HtmlPage page1 = webClient.getPage("http://some_url");

    // Get the form that we are dealing with and within that form, 
    // find the submit button and the field that we want to change.
    final HtmlForm form = page1.getFormByName("myform");

    final HtmlSubmitInput button = form.getInputByName("submitbutton");
    final HtmlTextInput textField = form.getInputByName("userid");

    // Change the value of the text field
    textField.setValueAttribute("root");

    // Now submit the form by clicking the button and get back the second page.
    final HtmlPage page2 = button.click();
}

你可以在这里阅读更多。

于 2009-09-05T11:22:06.987 回答
3

如果您不想直接谈论 HTTP(为什么?),请查看Watij

它允许您在 Java 进程中调用浏览器 (IE) 作为 COM 控件,通过使用其文档 ID 等浏览页面元素,填写表单并按下按钮。因为它正在运行浏览器,所以 Javascript 将正常运行(就像您手动执行此操作一样)。

于 2009-09-05T11:41:56.477 回答
0

您可能需要编写一个 Java Applet,因为除了发送直接请求之外,唯一的其他方法就是让它与浏览器交互。

当然,要使其正常工作,您必须将小程序嵌入到页面中。如果您不控制页面,则无法执行此操作。如果您确实控制了页面,那么您还不如使用 Javascript,而不是尝试让 Java Applet 来做这件事,这会更加麻烦和困难。

只是为了澄清一下,您在创建 HTTP 请求时遇到了什么问题,为什么要使用不同的方法?

于 2009-09-05T11:19:22.717 回答