com.gargoylesoftware.htmlunit.WebClient类的使用及代码示例

x33g5p2x  于2022-02-02 转载在 其他  
字(12.5k)|赞(0)|评价(0)|浏览(570)

本文整理了Java中com.gargoylesoftware.htmlunit.WebClient类的一些代码示例,展示了WebClient类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。WebClient类的具体详情如下:
包路径:com.gargoylesoftware.htmlunit.WebClient
类名称:WebClient

WebClient介绍

[英]The main starting point in HtmlUnit: this class simulates a web browser.

A standard usage of HtmlUnit will start with using the #getPage(String) method (or #getPage(URL)) to load a first Pageand will continue with further processing on this page depending on its type.

Example:

final WebClient webClient = new WebClient(); final HtmlPage startPage = webClient.getPage("http://htmlunit.sf.net"); assertEquals("HtmlUnit - Welcome to HtmlUnit", startPage. HtmlPage#getTitleText()());

Note: a WebClient instance is not thread safe. It is intended to be used from a single thread.
[中]HtmlUnit的主要出发点是:这个类模拟web浏览器。
HtmlUnit的标准用法是首先使用#getPage(String)方法(或#getPage(URL))加载第一个页面,然后根据页面类型继续在此页面上进行进一步处理。
例子:
final WebClient webClient = new WebClient(); final HtmlPage startPage = webClient.getPage("http://htmlunit.sf.net"); assertEquals("HtmlUnit - Welcome to HtmlUnit", startPage. HtmlPage#getTitleText()());
注意:WebClient实例不是线程安全的。它的用途是从一根线开始使用。

代码示例

代码示例来源:origin: spring-projects/spring-framework

@Test
public void verifyExampleInClassLevelJavadoc() throws Exception {
  Assume.group(TestGroup.PERFORMANCE);
  WebClient webClient = new WebClient();
  MockMvc mockMvc = MockMvcBuilders.standaloneSetup().build();
  MockMvcWebConnection mockConnection = new MockMvcWebConnection(mockMvc, webClient);
  WebRequestMatcher cdnMatcher = new UrlRegexRequestMatcher(".*?//code.jquery.com/.*");
  WebConnection httpConnection = new HttpWebConnection(webClient);
  webClient.setWebConnection(
      new DelegatingWebConnection(mockConnection, new DelegateWebConnection(cdnMatcher, httpConnection)));
  Page page = webClient.getPage("http://code.jquery.com/jquery-1.11.0.min.js");
  assertThat(page.getWebResponse().getStatusCode(), equalTo(200));
  assertThat(page.getWebResponse().getContentAsString(), not(isEmptyString()));
}

代码示例来源:origin: javaee-samples/javaee7-samples

@Before
public void setUp() {
  webClient = new WebClient();
  webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
}

代码示例来源:origin: spring-projects/spring-framework

private void storeCookies(WebRequest webRequest, javax.servlet.http.Cookie[] cookies) {
  Date now = new Date();
  CookieManager cookieManager = this.webClient.getCookieManager();
  for (javax.servlet.http.Cookie cookie : cookies) {
    if (cookie.getDomain() == null) {
      cookie.setDomain(webRequest.getUrl().getHost());
    }
    Cookie toManage = createCookie(cookie);
    Date expires = toManage.getExpires();
    if (expires == null || expires.after(now)) {
      cookieManager.addCookie(toManage);
    }
    else {
      cookieManager.removeCookie(toManage);
    }
  }
}

代码示例来源:origin: javaee-samples/javaee7-samples

@After
public void tearDown() {
  webClient.getCookieManager().clearCookies();
  webClient.close();
}

代码示例来源:origin: konsoletyper/teavm

private void cleanUp() {
  Page p = page.get();
  if (p != null) {
    p.cleanUp();
  }
  for (WebWindow window : webClient.get().getWebWindows()) {
    window.getJobManager().removeAllJobs();
  }
  page.remove();
  webClient.get().close();
  webClient.remove();
}

代码示例来源:origin: stapler/stapler

/**
 * Tests that an anonymous object can be bound.
 */
public void testAnonymousBind() throws Exception {
  WebClient wc = new WebClient();
  HtmlPage page = wc.getPage(new URL(url, "/bindAnonymous"));
  page.executeJavaScript("v.xyz('hello');");
  assertEquals("hello",anonymousValue);
}

代码示例来源:origin: stapler/stapler

@Issue("SECURITY-390")
public void testTraceXSS() throws Exception {
  WebClient wc = new WebClient();
  wc.setThrowExceptionOnFailingStatusCode(false);
  WebResponse rsp;
  Dispatcher.TRACE = true;
  try {
    rsp = wc.getPage(new URL(this.url, "thing/<button>/x")).getWebResponse();
  } finally {
    Dispatcher.TRACE = false;
  }
  assertEquals(HttpServletResponse.SC_NOT_FOUND, rsp.getStatusCode());
  String html = rsp.getContentAsString();
  assertTrue(html, html.contains("&lt;button&gt;"));
  assertFalse(html, html.contains("<button>"));
}
public Object getThing(String name) {

代码示例来源:origin: stapler/stapler

public void testStaplerProxy() throws Exception {
  WebClient wc = new WebClient();
  Page p = wc.getPage(new URL(url, "staplerProxyOK"));
  assertEquals(200, p.getWebResponse().getStatusCode());
  try {
    p = wc.getPage(new URL(url, "staplerProxyFail"));
    fail("expected failure");
  } catch (FailingHttpStatusCodeException ex) {
    assertEquals(404, ex.getStatusCode());
  }
  assertTrue(staplerProxyOK.counter > 0);
  assertTrue(staplerProxyFail.counter > 0);
}

代码示例来源:origin: stapler/stapler

public void testMainFeature() throws Exception {
  WebClient wc = new WebClient();
  HtmlPage page = wc.getPage(new URL(url, "/form.html"));
  HtmlForm f = page.getFormByName("main");
  f.getInputByName("json").setValueAttribute("{\"first\":\"Kohsuke\",\"last\":\"Kawaguchi\"}");
  f.submit();
}

代码示例来源:origin: stapler/stapler

public void testArbitraryWebMethodName() throws Exception {
  WebClient wc = new WebClient();
  TextPage p = wc.getPage(new URL(url, "arbitraryWebMethodName"));
  assertEquals("I'm index", p.getContent());
  p = wc.getPage(new URL(url, "arbitraryWebMethodName/theNeedful"));
  assertEquals("DTN", p.getContent());
}

代码示例来源:origin: weld/core

@Test
public void testELWithParameters(@ArquillianResource URL baseURL) throws Exception {
  WebClient client = new WebClient();
  HtmlPage page = client.getPage(new URL(baseURL, "charlie.jsf"));
  page.asXml();
  HtmlSpan oldel = getFirstMatchingElement(page, HtmlSpan.class, "oldel");
  assertNotNull(oldel);
  final String charlie = "Charlie";
  assertEquals(charlie, oldel.asText());
  HtmlSpan newel = getFirstMatchingElement(page, HtmlSpan.class, "newel");
  assertNotNull(newel);
  assertEquals(charlie, newel.asText());
}

代码示例来源:origin: org.apache.shale/shale-test

/**
 * <p>Set up the instance variables required for this test case.</p>
 *
 * @exception Exception if an error occurs
 */
protected void setUp() throws Exception {
  // Calculate the URL for the installed "systest" web application
  String url = System.getProperty("url");
  this.url = new URL(url + "/");
  // Initialize HtmlUnit constructs for this test case
  webClient = new WebClient();
}

代码示例来源:origin: com.github.albfernandez.test-jsf/jsf-test-scriptunit

protected void setupQunit(FrameworkMethod method, Object target) throws FailingHttpStatusCodeException, IOException {        
  URL URL = new URL(DEFAULT_URL+"/");
  setupWebClient();
  String content = buildContent(method,target);
  mockConnection.setResponse(URL, content);
  page = webClient.getPage(URL);
  webClient.waitForBackgroundJavaScriptStartingBefore(4 * 60 * 1000);
}

代码示例来源:origin: com.epam.gepard/gepard-rest

private void setTicketFieldValue(final GepardTestClass tc, final String ticket, final String fieldName, final String value) throws IOException {
  String jiraSetFieldPage = getIssueFieldSetValueUrl(ticket);
  WebRequest requestSettings = new WebRequest(new URL(jiraSetFieldPage), HttpMethod.PUT);
  requestSettings.setAdditionalHeader("Content-type", "application/json");
  requestSettings.setRequestBody("{ \"fields\": {\"" + fieldName + "\": \"" + value + "\"} }");
  try {
    UnexpectedPage infoPage = webClient.getPage(requestSettings);
    if (infoPage.getWebResponse().getStatusCode() == HTTP_RESPONSE_OK) {
      tc.logComment("Field: '" + fieldName + "' of Ticket: " + ticket + " was updated to value: '" + value + "' successfully.");
    } else {
      throw new SimpleGepardException("Ticket: " + ticket + " field: " + fieldName + " update failed, status code: " + infoPage.getWebResponse().getStatusCode());
    }
  } catch (FailingHttpStatusCodeException e) {
    throw new SimpleGepardException("Ticket: " + ticket + " field: " + fieldName + " update failed.", e);
  }
}

代码示例来源:origin: org.jboss.cdi.tck/cdi-tck-impl

@Test
@SpecAssertion(section = CONVERSATION_CONTEXT_EE, id = "m")
public void testConversationPropagatedOverRedirect() throws Exception {
  WebClient webClient = new WebClient();
  HtmlPage storm = webClient.getPage(getPath("storm.jsf"));
  // Begin long-running conversation
  HtmlSubmitInput beginConversationButton = getFirstMatchingElement(storm, HtmlSubmitInput.class,
      "beginConversationButton");
  storm = beginConversationButton.click();
  // Set input value
  HtmlTextInput stormStrength = getFirstMatchingElement(storm, HtmlTextInput.class, "stormStrength");
  stormStrength.setValueAttribute(REDIRECT_STORM_STRENGTH);
  String stormCid = getCid(storm);
  // Submit value and redirect to the next form
  HtmlSubmitInput lighteningButton = getFirstMatchingElement(storm, HtmlSubmitInput.class, "lighteningButton");
  HtmlPage lightening = lighteningButton.click();
  assertTrue(lightening.getWebResponse().getWebRequest().getUrl().toString().contains("lightening.jsf"));
  assertEquals(stormCid, getCid(lightening));
  stormStrength = getFirstMatchingElement(lightening, HtmlTextInput.class, "stormStrength");
  assertEquals(stormStrength.getValueAttribute(), REDIRECT_STORM_STRENGTH);
}

代码示例来源:origin: org.jboss.jsr299.tck/jsr299-tck-impl

@Test(groups = { "contexts" })
@SpecAssertion(section = "6.7.4", id = "m")
public void testConversationPropagatedOverRedirect() throws Exception
{
 WebClient webClient = new WebClient();
 HtmlPage storm = webClient.getPage(getPath("storm.jsf"));
 HtmlSubmitInput beginConversationButton = getFirstMatchingElement(storm, HtmlSubmitInput.class, "beginConversationButton");
 storm = beginConversationButton.click();
 HtmlTextInput stormStrength = getFirstMatchingElement(storm, HtmlTextInput.class, "stormStrength");
 stormStrength.setValueAttribute(REDIRECT_STORM_STRENGTH);
 String stormCid = getCid(storm);
 HtmlSubmitInput lighteningButton = getFirstMatchingElement(storm, HtmlSubmitInput.class, "lighteningButton");
 HtmlPage lightening = lighteningButton.click();
 assert lightening.getWebResponse().getRequestUrl().toString().contains("lightening.jsf");
 assert stormCid.equals(getCid(lightening));
 stormStrength = getFirstMatchingElement(lightening, HtmlTextInput.class, "stormStrength");
 assert stormStrength.getValueAttribute().equals(REDIRECT_STORM_STRENGTH);
}

代码示例来源:origin: org.jboss.cdi.tck/cdi-tck-impl

@Test(groups = {INTEGRATION, ASYNC_SERVLET})
@SpecAssertion(section = APPLICATION_CONTEXT_EE, id = "ae")
public void testApplicationContextActiveOnTimeout() throws Exception {
  WebClient webClient = new WebClient();
  webClient.setThrowExceptionOnFailingStatusCode(false);
  webClient.getPage(getPath(AsyncServlet.TEST_TIMEOUT));
  TextPage results = webClient.getPage(contextPath + "Status");
  assertTrue(results.getContent().contains("onTimeout: true"));
}

代码示例来源:origin: weld/core

public static JsonObject getPageAsJSONObject(String path, URL url, WebClient client) throws IOException {
  if (client == null) {
    client = new WebClient();
  }
  JsonReader jsonReader = Json.createReader(client.getPage(url.toString().concat(path)).getWebResponse().getContentAsStream());
  return jsonReader.readObject();
}

代码示例来源:origin: org.jvnet.hudson/htmlunit

final WebWindow window = openTargetWindow(opener, windowName, "_blank");
final HtmlPage openerPage = (HtmlPage) opener.getEnclosedPage();
if (url != null) {
  try {
    final WebRequestSettings settings = new WebRequestSettings(url);
    if (!getBrowserVersion().isIE() && openerPage != null) {
      final String referer = openerPage.getWebResponse().getRequestSettings().getUrl().toExternalForm();
      settings.setAdditionalHeader("Referer", referer);
    getPage(window, settings);
  initializeEmptyWindow(window);
  if (openerPage != null) {
    final Window jsWindow = (Window) window.getScriptObject();
    jsWindow.setDomNode(openerPage);
    jsWindow.jsxGet_document().setDomNode(openerPage);

代码示例来源:origin: org.jvnet.hudson/htmlunit

/**
 * <p><span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span></p>
 *
 * Opens a new dialog window.
 * @param url the URL of the document to load and display
 * @param opener the web window that is opening the dialog
 * @param dialogArguments the object to make available inside the dialog via <tt>window.dialogArguments</tt>
 * @return the new dialog window
 * @throws IOException if there is an IO error
 */
public DialogWindow openDialogWindow(final URL url, final WebWindow opener, final Object dialogArguments)
  throws IOException {
  WebAssert.notNull("url", url);
  WebAssert.notNull("opener", opener);
  final DialogWindow window = new DialogWindow(this, dialogArguments);
  fireWindowOpened(new WebWindowEvent(window, WebWindowEvent.OPEN, null, null));
  final HtmlPage openerPage = (HtmlPage) opener.getEnclosedPage();
  final WebRequestSettings settings = new WebRequestSettings(url);
  if (!getBrowserVersion().isIE()) {
    final String referer = openerPage.getWebResponse().getRequestSettings().getUrl().toExternalForm();
    settings.setAdditionalHeader("Referer", referer);
  }
  getPage(window, settings);
  return window;
}

相关文章

WebClient类方法