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.
June 25, 2009 at 8:29 am |
Hi,
Thanks for your post.
Yes, it is not easy, but also real browsers don’t provide a way for you to direct post a request, you have to go to a page, and click a link, then it will post.
HtmlUnit main usage is simulating real browsers usage, and customized actions would need the user to dig into the API a little.
June 25, 2009 at 8:32 am |
Very true! My problem was that I needed to test how Facebook notified my application when a user removed it… and Facebook does it via a POST.
Great work on HtmlUnit
August 6, 2009 at 8:27 am |
If HtmlUnit can’t correctly generate a form with JavaScript, we may still need to do a direct POST…
(Please remove my previous comment, thanks.)