HtmlUnit, how to post form without clicking submit button?

匿名 (未验证) 提交于 2019-12-03 01:36:02

问题:

I know that in HtmlUnit i can fireEvent submit on form and it will be posted. But what If I disabled javascript and would like to post a form using some built in function?

I've checked the javadoc and haven't found any way to do this. It is strange that there is no such function in HtmlForm...


I read the javadoc and tutorial on htmlunit page and I Know that i can use getInputByName() and click it. BuT sometimes there are forms that don't have submit type button or even there is such button but without name attribute.

I am asking for help in such situation, this is why i am using fireEvent but it does not always work.

回答1:

You can use a 'temporary' submit button:

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


回答2:

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


回答3:

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

From 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(); } 


回答4:

How about getting use of built-in javascript support? Just fire submit event on that form:

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

The code supposes you want to submit first form on the site.

And if the submit forwards you to another site, just link the response to the page variable:

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


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