2011-09-27 86 views
13

我知道,在HtmlUnit我可以fireEvent提交表格,它会被张贴。但是,如果我禁用JavaScript,并想使用一些内置函数发布表单?HtmlUnit,如何在不点击提交按钮的情况下发布表单?

我检查了javadoc,并没有找到任何方法来做到这一点。奇怪的是,没有在HtmlForm控件没有这种功能...


我阅读页面的HtmlUnit的javadoc和教程,我知道我可以使用getInputByName()并单击它。 BuT有时候会有表单没有提交类型按钮 甚至有这样的按钮但没有名称属性。

我在这种情况下寻求帮助,这就是为什么我使用fireEvent但它并不总是工作。

+0

我建议你使用'HttpURLConnection',并按照指示概述[这里](HTTP:/ /stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests)。或者使用Apache的'HttpClient'类。 – mrkhrts

+0

再次检查JavaDoc :)或者还有简介 - >入门一节,就像Ransom Briggs所做的那样。我不会去mrkhrts的方法......它太低级 –

回答

2
final HtmlSubmitInput button = form.getInputByName("submitbutton"); 
final HtmlPage page2 = button.click() 

the htmlunit doc

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

    webClient.closeAllWindows(); 
} 
+2

OP被编辑,现在它说没有提交按钮。 – Gray

38

您可以使用 '临时' 的提交按钮:

WebClient client = new WebClient(); 
HtmlPage page = client.getPage("http://stackoverflow.com"); 

// create a submit button - it doesn't work with 'input' 
HtmlElement button = page.createElement("button"); 
button.setAttribute("type", "submit"); 

// append the button to the form 
HtmlElement form = ...; 
form.appendChild(button); 

// submit the form 
page = button.click(); 
+1

这是辉煌的 – Leo

+0

你我的朋友是一个天才!已经为此工作了一个星期了! – duffanpj

+0

这是解决方案,我过去用过很多瓷砖,从来没有任何问题。 –

7
WebRequest requestSettings = new WebRequest(new URL("http://localhost:8080/TestBox"), HttpMethod.POST); 

// Then we set the request parameters 
requestSettings.setRequestParameters(Collections.singletonList(new NameValuePair(InopticsNfcBoxPage.MESSAGE, Utils.marshalXml(inoptics, "UTF-8")))); 

// Finally, we can get the page 
HtmlPage page = webClient.getPage(requestSettings); 
1

如何获得的使用内置的JavaScript支持?只需在该表格上触发提交活动:

HtmlForm form = page.getForms().get(0); 
form.fireEvent(Event.TYPE_SUBMIT); 

该代码假设您要在网站上提交第一个表单。

而且,如果您提交转发到其他网站,只是链接响应页面变量:

HtmlForm form = page.getForms().get(0); 
page = (HtmlPage) form.fireEvent(Event.TYPE_SUBMIT).getNewPage(); 
相关问题