HttpUnit的基礎使用(一)

magic_dreamer發表於2010-06-28
HttpUnit的基礎使用(一)

首頁地址
http://httpunit.sourceforge.net/doc/cookbook.html

1.WebConversation is the center of HttpUnit
It is responsible for maintaining session context via cookies returned by the server.

we can get web response like this:
WebConversation wc = new WebConversation();
WebResponse resp = wc.getResponse( "http://www.httpunit.org/doc/cookbook.html" ); // read this page

And we can examine and follow links like this:
WebLink link = resp.getLinkWith( "response" );// find the link
System.out.println(link.getURLString());
System.out.println(link.getText());
link.click();// follow it
WebResponse jdoc = wc.getCurrentPage();
System.out.println(jdoc.getTitle());

the link text in cookbook.html is like this:
<a href="api/com/meterware/httpunit/WebResponse.html">response</a>

The WebResponse.getLinkWithImageText() method can look up links by examining the ALT text, or the HttpUnitOptions.setImagesTreatedAsAltText method can cause ALT text to be treated as ordinary searchable text.

We can deal with tables too:
WebTable table = resp.getTables()[0];
table.getRowCount()
table.getColumnCount()
table.getTableCell( 0, 2 )

String[][] colors = resp.getTables()[1].asText();
colors[0][0]

2.Working with forms
WebForm form = resp.getForms()[0]; // select the first form in the page
form.getParameterValue( "Name" )

the Name html element is the page is like this:
<input name="Name" type="text" value="La Cerentolla">

form.setParameter( "Food", "Italian" ); // select one of the permitted values for food
form.removeParameter( "CreditCard" ); // clear the check box
form.submit(); // submit the form

3.Working with frames
WebConversation wc = new WebConversation();
WebResponse top = wc.getResponse( "http://www.meterware.com/Frames.html" ); // read a page with two frames
WebResponse summary = wc.getFrameContents( "summary" ); // read the summary frame
WebLink link = summary.getLinkWith( "Cake Recipe" ); // find the link (which targets "details" );
link.click(); // click on it
WebResponse response= wc.getFrameContents( "details" ); // retrieve the details frame

相關文章