com.gargoylesoftware.htmlunit.HttpMethod Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.HttpMethod. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XMLHTTPRequest.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Prepares the WebRequest that will be sent.
 * @param content the content to send
 */
private void prepareRequest(final Object content) {
    if (content != null && content != Undefined.instance) {
        if (!"".equals(content) && HttpMethod.GET == webRequest_.getHttpMethod()) {
            webRequest_.setHttpMethod(HttpMethod.POST);
        }
        if (HttpMethod.POST == webRequest_.getHttpMethod()
                || HttpMethod.PUT == webRequest_.getHttpMethod()
                || HttpMethod.PATCH == webRequest_.getHttpMethod()) {
            if (content instanceof FormData) {
                ((FormData) content).fillRequest(webRequest_);
            }
            else {
                final String body = Context.toString(content);
                if (!body.isEmpty()) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Setting request body to: " + body);
                    }
                    webRequest_.setRequestBody(body);
                }
            }
        }
    }
}
 
Example #2
Source File: WebConnectionWrapperTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void wrapper() throws Exception {
    final List<NameValuePair> emptyList = Collections.emptyList();
    final WebResponseData data = new WebResponseData(new byte[]{}, HttpStatus.SC_OK, "", emptyList);
    final WebResponse response = new WebResponse(data, URL_FIRST, HttpMethod.GET, 0);
    final WebRequest wrs = new WebRequest(URL_FIRST);

    final WebConnection realConnection = new WebConnection() {
        @Override
        public WebResponse getResponse(final WebRequest request) {
            assertSame(wrs, request);
            return response;
        }
        @Override
        public void close() {
            // nothing
        }
    };

    try (WebConnectionWrapper wrapper = new WebConnectionWrapper(realConnection)) {
        assertSame(response, wrapper.getResponse(wrs));
    }
}
 
Example #3
Source File: CsrfIT.java    From krazo with Apache License 2.0 6 votes vote down vote up
/**
 * Checks that CSRF validation works if token sent as header instead of
 * form field.
 *
 * @throws Exception an error occurs or validation fails.
 */
@Test
public void testFormHeaderOk() throws Exception {
    HtmlPage page1 = webClient.getPage(webUrl + "resources/csrf");

    // Check response and CSRF header
    WebResponse res = page1.getWebResponse();
    assertEquals(Response.Status.OK.getStatusCode(), res.getStatusCode());
    assertNotNull(res.getResponseHeaderValue(CSRF_HEADER));

    WebRequest req = new WebRequest(new URL(webUrl + "resources/csrf"));
    req.setHttpMethod(HttpMethod.POST);
    req.setAdditionalHeader(CSRF_HEADER, res.getResponseHeaderValue(CSRF_HEADER));
    res = webClient.loadWebResponse(req);
    assertEquals(Response.Status.OK.getStatusCode(), res.getStatusCode());
}
 
Example #4
Source File: XMLHttpRequest3Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
private void testMethod(final HttpMethod method) throws Exception {
    final String content = "<html><head><script>\n"
        + "function test() {\n"
        + "  var req = new XMLHttpRequest();\n"
        + "  req.open('" + method.name().toLowerCase(Locale.ROOT) + "', 'foo.xml', false);\n"
        + "  req.send('');\n"
        + "}\n"
        + "</script></head>\n"
        + "<body onload='test()'></body></html>";

    final WebClient client = getWebClient();
    final MockWebConnection conn = new MockWebConnection();
    conn.setResponse(URL_FIRST, content);
    final URL urlPage2 = new URL(URL_FIRST, "foo.xml");
    conn.setResponse(urlPage2, "<foo/>\n", MimeType.TEXT_XML);
    client.setWebConnection(conn);
    client.getPage(URL_FIRST);

    final WebRequest request = conn.getLastWebRequest();
    assertEquals(urlPage2, request.getUrl());
    assertSame(method, request.getHttpMethod());
}
 
Example #5
Source File: HtmlForm2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void buttonSubmitWithFormMethod() throws Exception {
    final String html = "<!DOCTYPE html>\n"
        + "<html><head></head>\n"
        + "<body>\n"
        + "  <p>hello world</p>\n"
        + "  <form id='myForm' action='" + URL_SECOND
                            + "' method='" + HttpMethod.POST + "'>\n"
        + "    <button id='myButton' type='submit' formmethod='" + HttpMethod.GET
                    + "'>Submit with different form method</button>\n"
        + "  </form>\n"
        + "</body></html>";
    final String secondContent = "second content";

    getMockWebConnection().setResponse(URL_SECOND, secondContent);

    final WebDriver driver = loadPage2(html);
    driver.findElement(By.id("myButton")).click();

    assertEquals(2, getMockWebConnection().getRequestCount());
    assertEquals(URL_SECOND.toString(), getMockWebConnection().getLastWebRequest().getUrl());
    assertEquals(HttpMethod.GET, getMockWebConnection().getLastWebRequest().getHttpMethod());
}
 
Example #6
Source File: HtmlForm2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void inputTypeSubmitWithFormMethod() throws Exception {
    final String html = "<!DOCTYPE html>\n"
        + "<html><head></head>\n"
        + "<body>\n"
        + "  <p>hello world</p>\n"
        + "  <form id='myForm' action='" + URL_SECOND
                            + "' method='" + HttpMethod.POST + "'>\n"
        + "    <input id='myButton' type='submit' formmethod='" + HttpMethod.GET + "' />\n"
        + "  </form>\n"
        + "</body></html>";
    final String secondContent = "second content";

    getMockWebConnection().setResponse(URL_SECOND, secondContent);

    final WebDriver driver = loadPage2(html);
    driver.findElement(By.id("myButton")).click();

    assertEquals(2, getMockWebConnection().getRequestCount());
    assertEquals(URL_SECOND.toString(), getMockWebConnection().getLastWebRequest().getUrl());
    assertEquals(HttpMethod.GET, getMockWebConnection().getLastWebRequest().getHttpMethod());
}
 
Example #7
Source File: CsrfIT.java    From ozark with Apache License 2.0 6 votes vote down vote up
/**
 * Checks that CSRF validation works if token sent as header instead of
 * form field.
 *
 * @throws Exception an error occurs or validation fails.
 */
@Test
public void testFormHeaderOk() throws Exception {
    HtmlPage page1 = webClient.getPage(webUrl + "resources/csrf");

    // Check response and CSRF header
    WebResponse res = page1.getWebResponse();
    assertEquals(Response.Status.OK.getStatusCode(), res.getStatusCode());
    assertNotNull(res.getResponseHeaderValue(CSRF_HEADER));

    WebRequest req = new WebRequest(new URL(webUrl + "resources/csrf"));
    req.setHttpMethod(HttpMethod.POST);
    req.setAdditionalHeader(CSRF_HEADER, res.getResponseHeaderValue(CSRF_HEADER));
    res = webClient.loadWebResponse(req);
    assertEquals(Response.Status.OK.getStatusCode(), res.getStatusCode());
}
 
Example #8
Source File: XMLHTTPRequest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Prepares the WebRequest that will be sent.
 * @param content the content to send
 */
private void prepareRequest(final Object content) {
    if (content != null && !Undefined.isUndefined(content)) {
        if (!"".equals(content) && HttpMethod.GET == webRequest_.getHttpMethod()) {
            webRequest_.setHttpMethod(HttpMethod.POST);
        }
        if (HttpMethod.POST == webRequest_.getHttpMethod()
                || HttpMethod.PUT == webRequest_.getHttpMethod()
                || HttpMethod.PATCH == webRequest_.getHttpMethod()) {
            if (content instanceof FormData) {
                ((FormData) content).fillRequest(webRequest_);
            }
            else {
                final String body = Context.toString(content);
                if (!body.isEmpty()) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Setting request body to: " + body);
                    }
                    webRequest_.setRequestBody(body);
                }
            }
        }
    }
}
 
Example #9
Source File: DockerDirectiveGeneratorTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
private void assertGenerateDirective(@Nonnull AbstractDirective desc, @Nonnull String responseText) throws Exception {
    // First, make sure the expected response text actually matches the toGroovy for the directive.
    assertEquals(desc.toGroovy(true), responseText);

    // Then submit the form with the appropriate JSON (we generate it from the directive, but it matches the form JSON exactly)
    JenkinsRule.WebClient wc = r.createWebClient();
    WebRequest wrs = new WebRequest(new URL(r.getURL(), DirectiveGenerator.GENERATE_URL), HttpMethod.POST);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("json", staplerJsonForDescr(desc).toString()));
    // WebClient.addCrumb *replaces* rather than *adds*:
    params.add(new NameValuePair(r.jenkins.getCrumbIssuer().getDescriptor().getCrumbRequestField(), r.jenkins.getCrumbIssuer().getCrumb(null)));
    wrs.setRequestParameters(params);
    WebResponse response = wc.getPage(wrs).getWebResponse();
    assertEquals("text/plain", response.getContentType());
    assertEquals(responseText, response.getContentAsString().trim());
}
 
Example #10
Source File: HtmlForm2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void buttonWithFormEnctype() throws Exception {
    final String html = "<!DOCTYPE html>\n"
        + "<html><head></head>\n"
        + "<body>\n"
        + "  <p>hello world</p>\n"
        + "  <form id='myForm' action='" + URL_SECOND
                            + "' method='" + HttpMethod.POST
                            + "' enctype='" + FormEncodingType.URL_ENCODED.getName() + "'>\n"
        + "    <input type='file' value='file1'>\n"
        + "    <button id='myButton' type='submit' formenctype='" + FormEncodingType.MULTIPART.getName()
        + "'>Submit with different form encoding type</button>\n"
        + "  </form>\n"
        + "</body></html>";
    final String secondContent = "second content";

    getMockWebConnection().setResponse(URL_SECOND, secondContent);

    final WebDriver driver = loadPage2(html);
    driver.findElement(By.id("myButton")).click();

    assertEquals(2, getMockWebConnection().getRequestCount());
    assertEquals(URL_SECOND.toString(), getMockWebConnection().getLastWebRequest().getUrl());
    assertEquals(FormEncodingType.MULTIPART, getMockWebConnection().getLastWebRequest().getEncodingType());
}
 
Example #11
Source File: HtmlForm2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void inputTypeSubmitWithFormEnctype() throws Exception {
    final String html = "<!DOCTYPE html>\n"
        + "<html><head></head>\n"
        + "<body>\n"
        + "  <p>hello world</p>\n"
        + "  <form id='myForm' action='" + URL_SECOND
                            + "' method='" + HttpMethod.POST
                            + "' enctype='" + FormEncodingType.URL_ENCODED.getName()
                            + "'>\n"
        + "    <input type='file' value='file1'>\n"
        + "    <input id='myButton' type='submit' formenctype='" + FormEncodingType.MULTIPART.getName() + "' />\n"
        + "  </form>\n"
        + "</body></html>";
    final String secondContent = "second content";

    getMockWebConnection().setResponse(URL_SECOND, secondContent);

    final WebDriver driver = loadPage2(html);
    driver.findElement(By.id("myButton")).click();

    assertEquals(2, getMockWebConnection().getRequestCount());
    assertEquals(URL_SECOND.toString(), getMockWebConnection().getLastWebRequest().getUrl());
    assertEquals(FormEncodingType.MULTIPART, getMockWebConnection().getLastWebRequest().getEncodingType());
}
 
Example #12
Source File: HtmlForm2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts(DEFAULT = "application/x-www-form-urlencoded",
        IE = "multipart/form-data")
public void inputTypeImageWithFormEnctype() throws Exception {
    final String html = "<!DOCTYPE html>\n"
        + "<html><head></head>\n"
        + "<body>\n"
        + "  <p>hello world</p>\n"
        + "  <form id='myForm' action='" + URL_SECOND
                            + "' method='" + HttpMethod.POST
                            + "' enctype='" + FormEncodingType.MULTIPART.getName() + "'>\n"
        + "    <input id='myButton' type='image' formenctype='" + FormEncodingType.URL_ENCODED.getName() + "' />\n"
        + "  </form>\n"
        + "</body></html>";
    final String secondContent = "second content";

    getMockWebConnection().setResponse(URL_SECOND, secondContent);

    final WebDriver driver = loadPage2(html, URL_FIRST);
    driver.findElement(By.id("myButton")).click();

    assertEquals(URL_SECOND.toString(), getMockWebConnection().getLastWebRequest().getUrl());
    assertEquals(getExpectedAlerts()[0],
                getMockWebConnection().getLastWebRequest().getEncodingType().getName());
}
 
Example #13
Source File: TestServerFixture.java    From fixd with Apache License 2.0 6 votes vote down vote up
@Test
public void testStatefulRequests() throws Exception {
    
    server.handle(Method.PUT, "/name/:name")
          .with(200, "text/plain", "OK")
          .withSessionHandler(new PathParamSessionHandler());
    
    server.handle(Method.GET, "/name")
          .with(200, "text/plain", "Name: {name}");
    
    WebClient client = new WebClient();
    
    Page page = client.getPage(new WebRequest(new URL(
            "http://localhost:8080/name/Tim"), 
            HttpMethod.PUT));
    assertEquals(200, page.getWebResponse().getStatusCode());
    
    page      = client.getPage(new WebRequest(new URL(
            "http://localhost:8080/name"), 
            HttpMethod.GET));
    assertEquals("Name: Tim", page.getWebResponse().getContentAsString().trim());
}
 
Example #14
Source File: XMLHttpRequest.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Prepares the WebRequest that will be sent.
 * @param content the content to send
 */
private void prepareRequest(final Object content) {
    if (content != null
        && (HttpMethod.POST == webRequest_.getHttpMethod()
                || HttpMethod.PUT == webRequest_.getHttpMethod()
                || HttpMethod.PATCH == webRequest_.getHttpMethod())
        && content != Undefined.instance) {
        if (content instanceof FormData) {
            ((FormData) content).fillRequest(webRequest_);
        }
        else {
            final String body = Context.toString(content);
            if (!body.isEmpty()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Setting request body to: " + body);
                }
                webRequest_.setRequestBody(body);
            }
        }
    }
}
 
Example #15
Source File: HtmlTextAreaTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private void formSubmission(final String textAreaText, final String expectedValue) throws Exception {
    final String content
        = "<html><head><title>foo</title></head><body>\n"
        + "<form id='form1'>\n"
        + "<textarea name='textArea1'>" + textAreaText + "</textarea>\n"
        + "<input type='submit' id='mysubmit'/>\n"
        + "</form></body></html>";
    final HtmlPage page = loadPage(content);
    final MockWebConnection webConnection = getMockConnection(page);
    final HtmlForm form = page.getHtmlElementById("form1");

    final HtmlTextArea textArea = form.getTextAreaByName("textArea1");
    assertNotNull(textArea);

    final Page secondPage = page.getHtmlElementById("mysubmit").click();

    assertEquals("url", URL_FIRST + "?textArea1=" + expectedValue, secondPage.getUrl());
    assertSame("method", HttpMethod.GET, webConnection.getLastMethod());
}
 
Example #16
Source File: DoubleEquivalenceSubmissionTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void attack(int gameId, String mutant) throws FailingHttpStatusCodeException, IOException {
	WebRequest attackRequest = new WebRequest(new URL("http://localhost:8080" + Paths.BATTLEGROUND_GAME),
			HttpMethod.POST);
	// // Then we set the request parameters
	attackRequest.setRequestParameters(Arrays.asList(new NameValuePair[] {
			new NameValuePair("formType", "createMutant"), new NameValuePair("gameId", "" + gameId),
			// TODO Encoded somehow ?
			new NameValuePair("mutant", "" + mutant) }));
	// curl -X POST \
	// --data "formType=createMutant&gameId=${gameId}" \
	// --data-urlencode mutant@${mutant} \
	// --cookie "${cookie}" --cookie-jar "${cookie}" \
	// -w @curl-format.txt \
	// -s ${CODE_DEFENDER_URL}/multiplayergame
	browser.getPage(attackRequest);

}
 
Example #17
Source File: HtmlTextAreaTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void formSubmission_NewValue() throws Exception {
    final String content
        = "<html><head><title>foo</title></head><body>\n"
        + "<form id='form1'>\n"
        + "<textarea name='textArea1'>foo</textarea>\n"
        + "<input type='submit' id='mysubmit'/>\n"
        + "</form></body></html>";
    final HtmlPage page = loadPage(content);
    final MockWebConnection webConnection = getMockConnection(page);
    final HtmlForm form = page.getHtmlElementById("form1");

    final HtmlTextArea textArea = form.getTextAreaByName("textArea1");
    textArea.setText("Flintstone");
    final Page secondPage = page.getHtmlElementById("mysubmit").click();

    assertEquals("url", URL_FIRST + "?textArea1=Flintstone", secondPage.getUrl());
    assertSame("method", HttpMethod.GET, webConnection.getLastMethod());
}
 
Example #18
Source File: HtmlFormTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Test order of submitted parameters matches order of elements in form.
 * @throws Exception if the test fails
 */
@Test
public void submit_FormElementOrder() throws Exception {
    final String html
        = "<html><head></head><body><form method='post' action=''>\n"
        + "<input type='submit' name='dispatch' value='Save' id='submitButton'>\n"
        + "<input type='hidden' name='dispatch' value='TAB'>\n"
        + "</form></body></html>";
    final WebClient client = getWebClientWithMockWebConnection();

    final MockWebConnection webConnection = getMockWebConnection();
    webConnection.setDefaultResponse(html);

    final WebRequest request = new WebRequest(URL_FIRST, HttpMethod.POST);

    final HtmlPage page = client.getPage(request);
    final HtmlInput submitButton = page.getHtmlElementById("submitButton");
    submitButton.click();

    final List<NameValuePair> collectedParameters = webConnection.getLastParameters();
    final List<NameValuePair> expectedParameters = Arrays.asList(new NameValuePair[] {
        new NameValuePair("dispatch", "Save"),
        new NameValuePair("dispatch", "TAB"),
    });
    assertEquals(expectedParameters, collectedParameters);
}
 
Example #19
Source File: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testCSRFClientRegistration() throws Exception {
    // Login to the client page successfully
    try (WebClient webClient = setupWebClientIDP("alice", "ecila")) {
        final UriBuilder clientsUrl = oidcEndpointBuilder("/console/clients");
        login(clientsUrl, webClient);

        // Register a new client
        WebRequest request = new WebRequest(clientsUrl.build().toURL(), HttpMethod.POST);
        request.setRequestParameters(Arrays.asList(
            new NameValuePair("client_name", "bad_client"),
            new NameValuePair("client_type", "confidential"),
            new NameValuePair("client_redirectURI", "https://127.0.0.1"),
            new NameValuePair("client_audience", ""),
            new NameValuePair("client_logoutURI", ""),
            new NameValuePair("client_homeRealm", ""),
            new NameValuePair("client_csrfToken", "12345")));

        HtmlPage registeredClientPage = webClient.getPage(request);
        assertTrue(registeredClientPage.asXml().contains("Invalid CSRF Token"));
    }
}
 
Example #20
Source File: HelperUser.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void defend(int gameId, String test) throws FailingHttpStatusCodeException, IOException {
	WebRequest defendRequest = new WebRequest(new URL(codedefendersHome + Paths.BATTLEGROUND_GAME), HttpMethod.POST);
	// curl -X POST \
	// --data "formType=createTest&gameId=${gameId}" \
	// --data-urlencode test@${test} \
	// --cookie "${cookie}" --cookie-jar "${cookie}" \
	// -w @curl-format.txt \
	// -s ${CODE_DEFENDER_URL}/multiplayergame
	defendRequest.setRequestParameters(Arrays.asList(new NameValuePair[] {
			new NameValuePair("formType", "createTest"), new NameValuePair("gameId", "" + gameId),
			// TODO Encoded somehow ?
			new NameValuePair("test", "" + test) }));
	browser.getPage(defendRequest);
}
 
Example #21
Source File: SimpleServletServerTest.java    From wildfly-samples with MIT License 5 votes vote down vote up
@Test
public void testMyAnotherServlet() throws IOException, ServletException {
    SimpleServletServer server = new SimpleServletServer();
    server.start();
    WebClient webClient = new WebClient();
    TextPage page = webClient.getPage(BASE + "/MyAnotherServlet");
    assertEquals("Howdy World from GET", page.getContent());
    
    WebRequest request = new WebRequest(new URL(BASE + "/MyAnotherServlet"), HttpMethod.POST);
    page = webClient.getPage(request);
    assertEquals("Howdy World from POST", page.getContent());
    server.stop();
}
 
Example #22
Source File: DoubleEquivalenceSubmissionTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void doLogin() throws FailingHttpStatusCodeException, IOException {
	WebRequest loginRequest = new WebRequest(new URL("http://localhost:8080"+ Paths.LOGIN), HttpMethod.POST);
	// // Then we set the request parameters
	loginRequest.setRequestParameters(Arrays.asList(new NameValuePair[] {
			new NameValuePair("formType", "login"), new NameValuePair("username", user.getUsername()),
			new NameValuePair("password", password), }));
	// Finally, we can get the page
	HtmlPage retunToGamePage = browser.getPage(loginRequest);
}
 
Example #23
Source File: DoubleEquivalenceSubmissionTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void startGame(int gameID) throws FailingHttpStatusCodeException, IOException {

			WebRequest startGameRequest = new WebRequest(new URL("http://localhost:8080" + Paths.BATTLEGROUND_GAME),
					HttpMethod.POST);
			// // Then we set the request parameters
			startGameRequest.setRequestParameters(Arrays.asList(new NameValuePair[] {
					new NameValuePair("formType", "startGame"), new NameValuePair("gameId", "" + gameID) }));
			// Finally, we can get the page
			// Not sure why this returns TextPage and not HtmlPage
			browser.getPage(startGameRequest);

		}
 
Example #24
Source File: DrawPage.java    From keycloak-dropwizard-integration with Apache License 2.0 5 votes vote down vote up
public static LoginPage<DrawPage> openWithoutLogin(WebClient webClient, URL url, LocalDate parse)
        throws IOException {
    WebRequest request = new WebRequest(new URL(url.toString() + "/draw"), HttpMethod.POST);
    List<NameValuePair> parameters = new ArrayList<>();
    parameters.add(new NameValuePair("date", "2015-01-01"));
    request.setRequestParameters(parameters);
    return new LoginPage<>(webClient.getPage(request), DrawPage.class);
}
 
Example #25
Source File: HtmlUnitRequestBuilderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void buildRequestInputStream() throws Exception {
	String content = "some content that has length";
	webRequest.setHttpMethod(HttpMethod.POST);
	webRequest.setRequestBody(content);

	MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

	assertThat(IOUtils.toString(actualRequest.getInputStream()), equalTo(content));
}
 
Example #26
Source File: XMLHTTPRequest.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private boolean isPreflight() {
    final HttpMethod method = webRequest_.getHttpMethod();
    if (method != HttpMethod.GET && method != HttpMethod.HEAD && method != HttpMethod.POST) {
        return true;
    }
    for (final Entry<String, String> header : webRequest_.getAdditionalHeaders().entrySet()) {
        if (isPreflightHeader(header.getKey().toLowerCase(Locale.ROOT),
                header.getValue())) {
            return true;
        }
    }
    return false;
}
 
Example #27
Source File: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> getTokenJson(String authorizationCode, String clientId, String clientSecret)
    throws IOException {
    try (WebClient webClient = setupWebClientRP(clientId, clientSecret)) {
        WebRequest request = new WebRequest(oidcEndpoint("/oauth2/token"), HttpMethod.POST);

        request.setRequestParameters(Arrays.asList(
            new NameValuePair("client_id", clientId),
            new NameValuePair("grant_type", "authorization_code"),
            new NameValuePair("code", authorizationCode)));

        return new JsonMapObjectReaderWriter().fromJson(
            webClient.getPage(request).getWebResponse().getContentAsString());
    }
}
 
Example #28
Source File: HtmlIsIndexTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void formSubmission() throws Exception {
    final String html
        = "<html><head><title>foo</title></head><body>\n"
            + "<form id='form1' method='post'>\n"
            + "  <isindex prompt='enterSomeText'></isindex>\n"
            + "  <input type='submit' id='clickMe'>\n"
            + "</form></body></html>";
    final HtmlPage page = loadPage(html);
    final MockWebConnection webConnection = getMockConnection(page);

    final HtmlForm form = page.getHtmlElementById("form1");

    final HtmlElement element = form.getElementsByAttribute(
            "isindex", "prompt", "enterSomeText").get(0);
    if (element instanceof HtmlIsIndex) {
        final HtmlIsIndex isInput = (HtmlIsIndex) element;
        isInput.setValue("Flintstone");
        final Page secondPage = page.getHtmlElementById("clickMe").click();

        final List<NameValuePair> expectedParameters = new ArrayList<>();
        expectedParameters.add(new NameValuePair("enterSomeText", "Flintstone"));

        assertEquals("url", URL_FIRST, secondPage.getUrl());
        assertSame("method", HttpMethod.POST, webConnection.getLastMethod());
        assertEquals("parameters", expectedParameters, webConnection.getLastParameters());
    }
}
 
Example #29
Source File: HtmlAnchor2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void click_onClickHandler_javascriptDisabled() throws Exception {
    final String htmlContent
        = "<html><head><title>foo</title></head><body>\n"
        + "<a href='http://www.foo1.com' id='a1'>link to foo1</a>\n"
        + "<a href='http://www.foo2.com' id='a2' "
        + "onClick='alert(\"clicked\")'>link to foo2</a>\n"
        + "<a href='http://www.foo3.com' id='a3'>link to foo3</a>\n"
        + "</body></html>";
    final WebClient client = getWebClient();
    client.getOptions().setJavaScriptEnabled(false);

    final List<String> collectedAlerts = new ArrayList<>();
    client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setDefaultResponse(htmlContent);
    client.setWebConnection(webConnection);

    final HtmlPage page = client.getPage(URL_FIRST);
    final HtmlAnchor anchor = page.getHtmlElementById("a2");

    assertEquals(Collections.EMPTY_LIST, collectedAlerts);

    final HtmlPage secondPage = anchor.click();

    assertEquals(Collections.EMPTY_LIST, collectedAlerts);
    final List<?> expectedParameters = Collections.EMPTY_LIST;

    assertEquals("url", "http://www.foo2.com/", secondPage.getUrl());
    assertSame("method", HttpMethod.GET, webConnection.getLastMethod());
    assertEquals("parameters", expectedParameters, webConnection.getLastParameters());
}
 
Example #30
Source File: HtmlFormTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void submit_BadSubmitMethod() throws Exception {
    final String html
        = "<html><head><title>foo</title></head><body>\n"
        + "<form id='form1' method='put'>\n"
        + "  <input type='text' name='textfield' value='*'/>\n"
        + "  <input type='submit' name='button' id='button' value='foo'/>\n"
        + "</form></body></html>";
    final HtmlPage page = loadPage(html);
    final MockWebConnection webConnection = getMockConnection(page);
    page.getHtmlElementById("button").click();
    assertSame(HttpMethod.GET, webConnection.getLastMethod());
}