---
title: "htmlunit"
author: "quguilai"
date: "2014-05-13T23:12:46Z"
tags: []
categories: ["互联网"]
slug: "htmlunit"
draft: false
lastmod: "2014-05-13T23:12:46Z"
id: 2066074
url: "https://qgl.iteye.com/blog/2066074"
---

# 转  http://www.programcreek.com/java-api-examples/index.php?api=com.gargoylesoftware.htmlunit.WebClient

# Java Code Examples for com.gargoylesoftware.htmlunit.WebClient

&lt;iframe id="aswift\_0" style="list-style: none outside none; margin: 0px; padding: 0px; left: 0px; position: absolute; top: 0px;" name="aswift\_0" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" width="728" height="90"&gt;&lt;/iframe&gt;

The following code examples are extracted from open source projects. You can click ![](http://www.programcreek.com/java-api-examples/includes/images/like.png) to vote up the examples you like. The votes will be used to predict good API usage examples and more good examples will be extracted based on the votes.

Code Example 1:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project Tomcat-History, under directory /src/main/java/edu/rit/se/history/tomcat/scrapers/.

Source CVEDetails.java

```
publicstaticvoid main(String[] args)throwsFailingHttpStatusCodeException,MalformedURLException,IOException{// DOMConfigurator.configure("log4j.properties.xml");WebClient client =newWebClient();Scanner scanner =newScanner(newFile("temp.txt"));while(scanner.hasNextLine()){String cve = scanner.nextLine().trim();System.out.print(cve +"\t");HtmlPage page = client.getPage("http://www.cvedetails.com/cve-details.php?cve_id="+ cve);HtmlTable table = page.getHtmlElementById("cvssscorestable");for(int i =0; i <7; i++){String cellText = table.getRow(i).getCell(1).asText().split("\\(")[0];System.out.print(cellText +"\t");}System.out.print("\n");}
	scanner.close();
	client.closeAllWindows();}
```

Code Example 2:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project scalagwt-gwt, under directory /user/src/com/google/gwt/junit/.

Source RunStyleHtmlUnit.java

```
protectedvoid setupWebClient(WebClientwebClient){if(developmentMode){JavaScriptEngine hostedEngine =newHostedJavaScriptEngine(webClient,
        treeLogger);webClient.setJavaScriptEngine(hostedEngine);}}
```

Code Example 3:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project scalagwt-gwt, under directory /dev/core/test/com/google/gwt/core/ext/linker/impl/.

Source SelectionScriptJavaScriptTest.java

```
privateList<String> loadPage(String hostPage,CharSequence testScript)throwsFailingHttpStatusCodeException,MalformedURLException,IOException{WebClientwebClient=newWebClient();// Make a mock web connection that can return the host page and the test// scriptMockWebConnection webConnection =newMockWebConnection();
  webConnection.setDefaultResponse(hostPage,"text/html");
  webConnection.setResponse(new URL("http://foo.test/foo/test.Module.nocache.js"), testScript.toString(),"application/javascript");webClient.setWebConnection(webConnection);finalList<String> alerts =newArrayList<String>();webClient.setAlertHandler(newAlertHandler(){@Overridepublicvoid handleAlert(Page page,String msg){
      alerts.add(msg);}});webClient.getPage("http://foo.test/");return alerts;}
```

Code Example 4:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project TAMA-Web, under directory/tama.web/src/test/java/org/motechproject/tamafunctionalframework/framework/.

Source MyWebClientTest.java

```
@Testpublicvoid getPage()throwsIOException{WebClientwebClient= mock(WebClient.class);CookieManager cookieManager = mock(CookieManager.class);when(webClient.getCookieManager()).thenReturn(cookieManager);MyWebClient myWebClient=newMyWebClient(webClient);
    myWebClient.getPage("http://foo",newQueryParams().put("bar","baz").put("quack","quick"));ArgumentCaptor<String> stringArgumentCaptor =ArgumentCaptor.forClass(String.class);
    verify(webClient).getPage(stringArgumentCaptor.capture());
    assertEquals(true, stringArgumentCaptor.getValue().contains("http://foo"));
    assertEquals(true, stringArgumentCaptor.getValue().contains("bar=baz&"));
    assertEquals(true, stringArgumentCaptor.getValue().contains("quack=quick&"));}
```

Code Example 5:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project github-api, under directory /src/main/java/org/kohsuke/github/.

Source GitHub.java

```
WebClient createWebClient()throwsIOException{WebClient wc =newWebClient();
    wc.setJavaScriptEnabled(false);
    wc.setCssEnabled(false);HtmlPage pg =(HtmlPage)wc.getPage("https://github.com/login");HtmlForm f = pg.getForms().get(0);
    f.getInputByName("login").setValueAttribute(login);
    f.getInputByName("password").setValueAttribute(password);
    f.submit();return wc;}
```

Code Example 6:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project github-api, under directory /src/main/java/org/kohsuke/github/.

Source GHOrganization.java

```
publicList<GHRepository> getRepositoriesWithOpenPullRequests()throwsIOException{WebClient wc = root.createWebClient();HtmlPage pg =(HtmlPage)wc.getPage("https://github.com/organizations/"+login+"/dashboard/pulls");List<GHRepository> r =newArrayList<GHRepository>();for(HtmlAnchor e : pg.getElementById("js-issue-list").<HtmlAnchor>selectNodes(".//UL[@class='smallnav']/LI[not(@class='zeroed')]/A")){String a = e.getHrefAttribute();String name = a.substring(a.lastIndexOf('/')+1);
        r.add(getRepository(name));}return r;}
```

Code Example 7:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project github-api, under directory /src/main/java/org/kohsuke/github/.

Source GHRepository.java

```
publicvoid setEmailServiceHook(String address)throwsIOException{WebClient wc = root.createWebClient();HtmlPage pg =(HtmlPage)wc.getPage(getUrl()+"/admin");HtmlInput email =(HtmlInput)pg.getElementById("email_address");
    email.setValueAttribute(address);HtmlCheckBoxInput active =(HtmlCheckBoxInput)pg.getElementById("email[active]");
    active.setChecked(true);finalHtmlForm f = email.getEnclosingFormOrDie();
    f.submit((HtmlButton) f.getElementsByTagName("button").get(0));}
```

Code Example 8:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project shindig, under directory /java/server/src/test/java/org/apache/shindig/server/endtoend/.

Source EndToEndTest.java

```
@Beforepublicvoid setUp()throwsException{webClient=newWebClient();// NicelyResynchronizingAjaxController changes XHR calls from asynchronous// to synchronous, saving the test from needing to wait or sleep for XHR// completion.webClient.setAjaxController(newNicelyResynchronizingAjaxController());webClient.waitForBackgroundJavaScript(120000);// Closure can take a long time...webClient.setHTMLParserListener(HTMLParserListener.LOG_REPORTER);webClient.setTimeout(120000);// Closure can take a long time...

  alertHandler =newCollectingAlertHandler();webClient.setAlertHandler(alertHandler);
  token = createToken("canonical","john.doe");
  language =null;
  server.clearDataServiceError();}
```

Code Example 9:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project fred-official, under directory /generator/js/tests/src/freenet/.

Source PushTester.java

```
@SecondsLong(43)@TestType(Type.INTEGRATION)publicvoid testKeepalive()throwsException{WebClient c =newWebClient();String requestId =((HtmlPage) c.getPage(TEST_URL)).getElementById("requestId").getAttribute("value");
	c.closeAllWindows();if(c.getPage(TEST_URL_PREFIX +"/keepalive/?requestId="+ requestId).getWebResponse().getContentAsString().startsWith("SUCCESS")==false){thrownewException("Initial keepalive should be successfull");}Thread.sleep(43000);if(c.getPage(TEST_URL_PREFIX +"/keepalive/?requestId="+ requestId).getWebResponse().getContentAsString().startsWith("FAILURE")==false){thrownewException("Timeouted keepalive should have failed");}
	c.getPage(TEST_URL_PREFIX +"/leaving/?requestId="+ requestId);}
```

Code Example 10:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project fred-official, under directory /generator/js/tests/src/freenet/.

Source PushTester.java

```
@SecondsLong(4)@TestType(Type.ACCEPTANCE)publicvoid testPushing()throwsException{WebClient c =newWebClient();WebWindow w =newTopLevelWindow("1", c);
	c.setCurrentWindow(w);HtmlPage p = c.getPage(TEST_URL);Thread.sleep(4000);int current =Integer.parseInt(p.getElementById("content").getFirstChild().getFirstChild().getTextContent().trim());if(current <3|| current >5){thrownewException("The value is not in the expected interval:[3,5]. The current value:"+ current);}
	c.getPage(TEST_URL_PREFIX +"/leaving/?requestId="+ p.getElementById("requestId").getAttribute("value"));}
```

Code Example 11:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project fred-official, under directory /generator/js/tests/src/freenet/.

Source PushTester.java

```
@SecondsLong(12)@TestType(Type.ACCEPTANCE)publicvoid testConnectionSharing()throwsException{WebClient c =newWebClient();WebWindow w1 =newTopLevelWindow("1", c);WebWindow w2 =newTopLevelWindow("2", c);
	c.setCurrentWindow(w1);String requestId1 =((HtmlPage) c.getPage(TEST_URL)).getElementById("requestId").getAttribute("value");Thread.sleep(1000);
	c.setCurrentWindow(w2);String requestId2 =((HtmlPage) c.getPage(TEST_URL)).getElementById("requestId").getAttribute("value");Thread.sleep(500);
	enableDebug(w1);
	enableDebug(w2);Thread.sleep(10000);System.out.println(getLogForWindows(w1,w2));int current =Integer.parseInt(((HtmlPage) w1.getEnclosedPage()).getElementById("content").getFirstChild().getFirstChild().getTextContent().trim());if(current <9|| current >12){thrownewException("The value is not in the expected interval:[9,12] for Window 1. The current value:"+ current);}
	current =Integer.parseInt(((HtmlPage) w2.getEnclosedPage()).getElementById("content").getFirstChild().getFirstChild().getTextContent().trim());if(current <9|| current >12){thrownewException("The value is not in the expected interval:[9,12] for Window 2. The current value:"+ current);}if(getLogForWindows(w2).contains("pushnotifications")|| getLogForWindows(w1).contains("pushnotifications")==false){thrownewException("Window 2 is making permanent requests or Window 1 don't");}
	c.getPage(TEST_URL_PREFIX +"/leaving/?requestId="+ requestId1);
	c.getPage(TEST_URL_PREFIX +"/leaving/?requestId="+ requestId2);}
```

Code Example 12:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project fred-official, under directory /generator/js/tests/src/freenet/.

Source PushTester.java

```
@Only@SecondsLong(25)@TestType(Type.ACCEPTANCE)publicvoid testFailover()throwsException{WebClient c =newWebClient();WebWindow w1 =newTopLevelWindow("1", c);WebWindow w2 =newTopLevelWindow("2", c);
	c.setCurrentWindow(w1);
	c.getPage(TEST_URL);Thread.sleep(500);
	enableDebug(w1);Thread.sleep(500);
	c.setCurrentWindow(w2);
	c.getPage(TEST_URL);Thread.sleep(500);
	enableDebug(w2);Thread.sleep(4000);
	c.deregisterWebWindow(w1);Thread.sleep(20000);System.out.println(getLogForWindows(w1,w2));int current =Integer.parseInt(((HtmlPage) w2.getEnclosedPage()).getElementById("content").getFirstChild().getFirstChild().getTextContent().trim());if(current <23|| current >25){thrownewException("The value is not in the expected interval:[23,25] for Window 2. The current value:"+ current);}
	c.getPage(TEST_URL_PREFIX +"/leaving/?requestId="+((HtmlPage) w2.getEnclosedPage()).getElementById("requestId").getAttribute("value"));}
```

Code Example 13:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project fred-official, under directory /generator/js/tests/src/freenet/.

Source PushTester.java

```
@SecondsLong(42)@TestType(Type.INTEGRATION)publicvoid testCleanerNotificationRemoval()throwsException{WebClient c1 =newWebClient();WebClient c2 =newWebClient();String requestId1 =((HtmlPage) c1.getPage(TEST_URL)).getElementById("requestId").getAttribute("value");String requestId2 =((HtmlPage) c2.getPage(TEST_URL)).getElementById("requestId").getAttribute("value");System.out.println("Pages got");
	c1.closeAllWindows();
	c2.closeAllWindows();System.out.println("Windows closed");if(c1.getPage(TEST_URL_PREFIX +"/pushnotifications/?requestId="+ requestId1).getWebResponse().getContentAsString().startsWith("SUCCESS")==false){thrownewException("There should be a notification!");}System.out.println("Notifications working");for(int i =0; i <21; i++){Thread.sleep(2000);System.out.println("Sending keepalive:"+ i);if(c1.getPage(TEST_URL_PREFIX +"/keepalive/?requestId="+ requestId1).getWebResponse().getContentAsString().startsWith("SUCCESS")==false){thrownewException("Keepalive should be successful!");}}System.out.println("All keepalives sent");for(int i =0; i <20; i++){System.out.println("Getting notification:"+ i);if(newString(Base64.decodeStandard(c1.getPage(TEST_URL_PREFIX +"/pushnotifications/?requestId="+ requestId1).getWebResponse().getContentAsString().split("[:]")[1])).compareTo(requestId1)!=0){thrownewException("Only the first page should have notifications!");}}
	c1.getPage(TEST_URL_PREFIX +"/leaving/?requestId="+ requestId1);
	c2.getPage(TEST_URL_PREFIX +"/leaving/?requestId="+ requestId2);}
```

Code Example 14:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project fred-official, under directory /generator/js/tests/src/freenet/.

Source PushTester.java

```
@SecondsLong(0)@TestType(Type.INTEGRATION)publicvoid testLeaving()throwsException{WebClient c =newWebClient();String requestId =((HtmlPage) c.getPage(TEST_URL)).getElementById("requestId").getAttribute("value");if(c.getPage(TEST_URL_PREFIX +"/keepalive/?requestId="+ requestId).getWebResponse().getContentAsString().startsWith("SUCCESS")==false){thrownewException("Initial keepalive should be successfull");}if(c.getPage(TEST_URL_PREFIX +"/leaving/?requestId="+ requestId).getWebResponse().getContentAsString().startsWith("SUCCESS")==false){thrownewException("Leaving should always be successfull");}if(c.getPage(TEST_URL_PREFIX +"/keepalive/?requestId="+ requestId).getWebResponse().getContentAsString().startsWith("FAILURE")==false){thrownewException("Keepalive should fail after leaving");}}
```

Code Example 15:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project jasmine-maven-plugin, under directory /src/test/java/com/github/searls/jasmine/runner/.

Source SpecRunnerHtmlGeneratorPseudoIntegrationTest.java

```
privateHtmlPage getPage(String html)throwsException{MockWebConnection webConnection =newMockWebConnection();
  webConnection.setDefaultResponse(html);WebClientwebClient=newWebClient();webClient.setWebConnection(webConnection);webClient.setThrowExceptionOnScriptError(false);webClient.setIncorrectnessListener(newIncorrectnessListener(){publicvoid notify(String arg0,Object arg1){}});returnwebClient.getPage("http://blah");}
```

Code Example 16:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project jasmine-maven-plugin, under directory /src/main/java/com/github/searls/jasmine/coffee/.

Source CoffeeScript.java

```
@OverrideprotectedHtmlPage initialValue(){MockWebConnection webConnection =newMockWebConnection();WebClientwebClient=newWebClient();webClient.setWebConnection(webConnection);try{HtmlPage page =webClient.getPage(WebClient.URL_ABOUT_BLANK);
    page.executeJavaScript(ioUtilsWrapper.toString("/vendor/js/coffee-script.js"));return page;}catch(IOException e){thrownewRuntimeException(e);}}
```

Code Example 17:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project Opencast-Matterhorn, under directory /modules/matterhorn-ingest-service-impl/src/test/java/org/opencastproject/ingest/impl/.

Source QUnitTest.java

```
@Testpublicvoid runQUnitTests()throwsException{WebClient client =newWebClient();
  client.setJavaScriptEnabled(true);HtmlPage page = client.getPage("file:///"+ testFile.getAbsolutePath());// try 20 times to wait .5 second each for filling the page.HtmlElement element =null;for(int i =0; i <20;++i){try{
      element = page.getHtmlElementById("qunit-testresult");break;}catch(ElementNotFoundException e){synchronized(page){System.out.println("Waiting for JavaScript tests...");
        page.wait(500);}}}System.out.println(element.getTextContent());
  assertTrue(element.getTextContent().contains(", 0 failed."));}
```

Code Example 18:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project fb-desktop-notifications, under directory /DesktopNotify/src/.

Source JSONQuery.java

```
publicstaticvoidEnquire(StringAccessCode)throwsException{int cont;do{//System.out.println("Entered loop in JSONQuery");//final com.gargoylesoftware.htmlunit.WebClientwebClient = new WebClient();JavaScriptPage page=webClient.getPage("https://graph.facebook.com/fql?q=SELECT+thread_id+,+message_count+,+snippet+,+snippet_author+FROM+thread+WHERE+folder_id=0+and+unread!=0&access_token="+AccessCode);String jsonObj = page.getContent();
		cont =JSONParse(jsonObj,AccessCode);if(cont==0){System.out.println("No new messages");}Thread.currentThread().sleep(10000);}while(cont!=-1);}
```

Code Example 19:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project fb-desktop-notifications, under directory /DesktopNotify/src/.

Source GUIMain.java

```
publicstaticvoid main(String[] args)throwsException{
	display =newDisplay();
	shell =newShell(display);GridLayout layout =newGridLayout();
	layout.numColumns =1;
	shell.setLayout(layout);GUIMain main =newGUIMain();
	
	main.webClient=newWebClient();JSONQuery.webClient= main.webClient;MessageQuery.webClient= main.webClient;OAuthSession.webClient= main.webClient;finalLabel label =newLabel(shell, SWT.CENTER);
	label.setText("DESKTOP NOTIFY 1.0");
	label.setLayoutData(newGridData(SWT.CENTER, SWT.TOP,true,true,1,1));
	
	main.createWidgets();
	
	
	
	shell.pack();
	shell.open();while(!(shell.isDisposed())){if(!display.readAndDispatch())
			display.sleep();}
	display.dispose();System.exit(0);}
```

Code Example 20:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project jsfunit, under directory /jboss-jsfunit-examples/jboss-jsfunit-examples-ajax4jsf/src/test/java/org/jboss/jsfunit/example/ajax4jsf/.

Source FaceletsErrorPageTest.java

```
publicvoid testIsNotFaceletsErrorPage()throwsIOException{WebClientSpec wcSpec =newWebClientSpec("/index.jsf");WebClientwebClient= wcSpec.getWebClient();JSFUnitWebConnection webConnection =(JSFUnitWebConnection)webClient.getWebConnection();
   webConnection.addListener(this);newJSFSession(wcSpec);

   assertNotNull(this.latestResponse);
   assertFalse(FaceletsErrorPageException.isFaceletsErrorPage(this.latestResponse));}
```

Code Example 21:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project jsfunit, under directory /jboss-jsfunit-examples/jboss-jsfunit-examples-ajax4jsf/src/test/java/org/jboss/jsfunit/example/ajax4jsf/.

Source FaceletsErrorPageTest.java

```
publicvoid testIsFaceletsErrorPage()throwsIOException{WebClientSpec wcSpec =newWebClientSpec("/badIndex.jsf");WebClientwebClient= wcSpec.getWebClient();JSFUnitWebConnection webConnection =(JSFUnitWebConnection)webClient.getWebConnection();
   webConnection.addListener(this);try{newJSFSession(wcSpec);
      fail("Expected FaceleteErrorPageException");}catch(FaceletsErrorPageException e){// Because of the exception, afterRequest was never called for me
      assertNull(this.latestResponse);}}
```

Code Example 22:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project jsfunit, under directory /jboss-jsfunit-examples/jboss-jsfunit-examples-hellojsf/jboss-jsfunit-examples-hellojsf-pathmapped/src/test/java/org/jboss/jsfunit/jsfsession/hellojsf/.

Source ManualInvokeTest.java

```
publicvoid testInvokeWithServletTestRunner()throwsException{WebClientwebClient=newWebClient();Page page =webClient.getPage(contextURL +"/ServletTestRunner?suite=org.jboss.jsfunit.jsfsession.hellojsf.HelloJSFIntegrationTest");String text =((XmlPage)page).asXml();
   assertTrue(text.contains("errors=\"0\"")&& text.contains("tests=\"5\"")&& text.contains("failures=\"0\"")&& text.contains("name=\"org.jboss.jsfunit.jsfsession.hellojsf.HelloJSFIntegrationTest\""));}
```

Code Example 23:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project jsfunit, under directory /jboss-jsfunit-examples/jboss-jsfunit-examples-hellojsf/jboss-jsfunit-examples-hellojsf-jsfunit/src/test/java/org/jboss/jsfunit/jsfsession/hellojsf/.

Source ManualInvokeTest.java

```
publicvoid testInvokeWithServletTestRunner()throwsException{WebClientwebClient=newWebClient();Page page =webClient.getPage(contextURL +"/ServletTestRunner?suite=org.jboss.jsfunit.jsfsession.hellojsf.HelloJSFIntegrationTest");String text =((XmlPage)page).asXml();
   assertTrue(text.contains("errors=\"0\"")&& text.contains("tests=\"5\"")&& text.contains("failures=\"0\"")&& text.contains("name=\"org.jboss.jsfunit.jsfsession.hellojsf.HelloJSFIntegrationTest\""));}
```

Code Example 24:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project jsfunit, under directory /jboss-jsfunit-examples/jboss-jsfunit-examples-hellojsf/jboss-jsfunit-examples-hellojsf-jsfunit/src/test/java/org/jboss/jsfunit/jsfsession/hellojsf/.

Source ManualInvokeTest.java

```
publicvoid testPassServletRedirectorParams()throwsException{WebClientwebClient=newWebClient();Page page =webClient.getPage(contextURL +"/ServletTestRunner?suite=org.jboss.jsfunit.jsfsession.hellojsf.PassServletRedirectParamsTest&foo=bar");String text =((XmlPage)page).asXml();
   assertTrue(text.contains("errors=\"0\"")&& text.contains("tests=\"1\"")&& text.contains("failures=\"0\"")&& text.contains("name=\"org.jboss.jsfunit.jsfsession.hellojsf.PassServletRedirectParamsTest\""));}
```

Code Example 25:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project jsfunit, under directory /jboss-jsfunit-examples/jboss-jsfunit-examples-hellojsf/jboss-jsfunit-examples-hellojsf-jsfunit/src/test/java/org/jboss/jsfunit/jsfsession/hellojsf/.

Source CustomWebClientTest.java

```
publicvoid testCustomizedWebConversation()throwsIOException{WebClientSpec wcSpec =newWebClientSpec("/index.faces");WebClientwebClient= wcSpec.getWebClient();
   assertNotNull(webClient);
   assertEquals(BrowserVersion.getDefault(),webClient.getBrowserVersion());webClient.addRequestHeader("mycoolheader","mycoolvalue");JSFSession jsfSession =newJSFSession(wcSpec);JSFServerSession server = jsfSession.getJSFServerSession();Object headerValue = server.getFacesContext().getExternalContext().getRequestHeaderValuesMap().get("mycoolheader");
   assertEquals("mycoolvalue",((String[])headerValue)[0]);}
```

Code Example 26:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project jsfunit, under directory /jboss-jsfunit-examples/jboss-jsfunit-examples-hellojsf/jboss-jsfunit-examples-hellojsf-jsfunit/src/test/java/org/jboss/jsfunit/jsfsession/hellojsf/.

Source CustomWebClientTest.java

```
publicvoid testGetWebClient()throwsIOException{WebClientSpec wcSpec =newWebClientSpec("/index.faces");
   assertEquals("/index.faces", wcSpec.getInitialPage());JSFSession jsfSession =newJSFSession(wcSpec);JSFClientSession client = jsfSession.getJSFClientSession();WebClientwebClientFromJSFSession = jsfSession.getWebClient();
   assertEquals(wcSpec.getWebClient(),webClientFromJSFSession);webClientFromJSFSession.addRequestHeader("mycoolheader","mycoolvalue");
   client.click("submit_button");JSFServerSession server = jsfSession.getJSFServerSession();Object headerValue = server.getFacesContext().getExternalContext().getRequestHeaderValuesMap().get("mycoolheader");
   assertEquals("mycoolvalue",((String[])headerValue)[0]);}
```

Code Example 27:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project jsfunit, under directory /jboss-jsfunit-examples/jboss-jsfunit-examples-hellojsf/jboss-jsfunit-examples-hellojsf-jee6/src/test/java/org/jboss/jsfunit/jsfsession/hellojsf/.

Source ConsoleTest.java

```
@Overridepublicvoid setUp()throwsIOException{WebClientwebClient=newWebClient();
   consolePage =webClient.getPage("http://localhost:8080/jboss-jsfunit-examples-hellojsf-jee6/jsfunit/index.jsfunit");}
```

Code Example 28:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project jsfunit, under directory /jboss-jsfunit-examples/jsf2/src/test/java/org/jboss/jsfunit/jsf2/test/.

Source FaceletsErrorPageTest.java

```
publicvoid testIsNotFaceletsErrorPage()throwsIOException{WebClientSpec wcSpec =newWebClientSpec("/index.jsf");WebClientwebClient= wcSpec.getWebClient();JSFUnitWebConnection webConnection =(JSFUnitWebConnection)webClient.getWebConnection();
   webConnection.addListener(this);newJSFSession(wcSpec);

   assertNotNull(this.latestResponse);
   assertFalse(FaceletsErrorPageException.isFaceletsErrorPage(this.latestResponse));}
```

Code Example 29:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project jsfunit, under directory /jboss-jsfunit-examples/jsf2/src/test/java/org/jboss/jsfunit/jsf2/test/.

Source FaceletsErrorPageTest.java

```
publicvoid testIsFaceletsErrorPage()throwsIOException{WebClientSpec wcSpec =newWebClientSpec("/badIndex.jsf");WebClientwebClient= wcSpec.getWebClient();JSFUnitWebConnection webConnection =(JSFUnitWebConnection)webClient.getWebConnection();
   webConnection.addListener(this);try{newJSFSession(wcSpec);}catch(FaceletsErrorPageException e){// ignore}

   assertNotNull(this.latestResponse);
   assertTrue(FaceletsErrorPageException.isFaceletsErrorPage(this.latestResponse));}
```

Code Example 30:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project jsfunit, under directory /jboss-jsfunit-core/src/main/java/org/jboss/jsfunit/framework/.

Source WebConversationFactory.java

```
staticvoid makeWebClient(WebClientSpec wcSpec){WebClient wc =null;String proxyHost = wcSpec.getProxyHost();if(proxyHost !=null) wc =newWebClient(wcSpec.getBrowserVersion(), 
                                             proxyHost, 
                                             wcSpec.getProxyPort());if(proxyHost ==null) wc =newWebClient(wcSpec.getBrowserVersion());
   wc.setAjaxController(newNicelyResynchronizingAjaxController());
   wc.setWebConnection(newJSFUnitWebConnection(wc.getWebConnection()));
   wcSpec.setWebClient(wc);HttpSession session = getSessionFromThreadLocal();if(session ==null){thrownewIllegalStateException("Can not find HttpSession.  Make sure JSFUnitFilter has run and your test extends org.apache.cactus.ServletTestCase.");}
   
   clearSession(session);
   session.setAttribute(WebClientSpec.SESSION_KEY, wcSpec);
   
   wcSpec.addCookie("JSESSIONID", session.getId());
   wcSpec.addCookie(JSF_UNIT_CONVERSATION_FLAG, JSF_UNIT_CONVERSATION_FLAG);}
```

Code Example 31:

  1 

![vote](http://www.programcreek.com/java-api-examples/includes/images/like.png)

From project yanel, under directory/src/resources/nutch/src/test/htmlunit/org/wyona/yanel/impl/resources/.

Source NutchResourceWebTest.java

```
publicint searchResults(String searchTerm)throwsException{finalWebClientwebClient=newWebClient();final URL url =new URL("http://127.0.0.1:8080/yanel/yanel-website/en/search.html");//final URL url = new URL(this.config.getString("baseUrl") + "yanel-website/en/search.html");finalHtmlPage searchPage =(HtmlPage)webClient.getPage(url);finalHtmlForm form = searchPage.getFormByName("search");finalHtmlSubmitInput button =(HtmlSubmitInput) form.getInputByName("submit");finalHtmlTextInput textField =(HtmlTextInput) form.getInputByName("query");
    textField.setValueAttribute(searchTerm);HtmlPage resultPage =(HtmlPage) button.click();String totalHits = resultPage.getHtmlElementById("resultHits").getAttributeValue("hits");returnInteger.parseInt(totalHits);}
```