HtmlUnit – How to do a POST

June 24, 2009

Background

I’ve just started using HtmlUnit (I also use Selenium but find it too slow for 90% of my testing).

HtmlUnit is generally easy to work with. Generally, it doesn’t need documentation as the Javadoc is useful and the methods are obvious. However, this is not the case for POST… so, here is how you do a POST đŸ™‚

How to do a POST in HtmlUnit

There really isn’t much to it – you just need to know what code to use:

final WebClient webClient = new WebClient();

// Instead of requesting the page directly we create a WebRequestSettings object
WebRequestSettings requestSettings = new WebRequestSettings(
  new URL("URL GOES HERE"), HttpMethod.POST);

// Then we set the request parameters
requestSettings.setRequestParameters(new ArrayList());
requestSettings.getRequestParameters().add(new NameValuePair("name of value to post", "value"));

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

Quite a lot of work for a simple… I imagine it won’t be hard to wrap this up into a neat POST method.