com.gargoylesoftware.htmlunit.FormEncodingType Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.FormEncodingType. 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
/**
 * @param name header name (MUST be lower-case for performance reasons)
 * @param value header value
 */
private static boolean isPreflightHeader(final String name, final String value) {
    if (HttpHeader.CONTENT_TYPE_LC.equals(name)) {
        final String lcValue = value.toLowerCase(Locale.ROOT);
        if (lcValue.startsWith(FormEncodingType.URL_ENCODED.getName())
            || lcValue.startsWith(FormEncodingType.MULTIPART.getName())
            || lcValue.startsWith("text/plain")) {
            return false;
        }
        return true;
    }
    if (HttpHeader.ACCEPT_LC.equals(name)
            || HttpHeader.ACCEPT_LANGUAGE_LC.equals(name)
            || HttpHeader.CONTENT_LANGUAGE_LC.equals(name)
            || HttpHeader.REFERER_LC.equals(name)
            || HttpHeader.ACCEPT_ENCODING_LC.equals(name)
            || HttpHeader.ORIGIN_LC.equals(name)) {
        return false;
    }
    return true;
}
 
Example #2
Source File: XMLHttpRequest.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * @param name header name (MUST be lower-case for performance reasons)
 * @param value header value
 */
private static boolean isPreflightHeader(final String name, final String value) {
    if (HttpHeader.CONTENT_TYPE_LC.equals(name)) {
        final String lcValue = value.toLowerCase(Locale.ROOT);
        if (lcValue.startsWith(FormEncodingType.URL_ENCODED.getName())
            || lcValue.startsWith(FormEncodingType.MULTIPART.getName())
            || lcValue.startsWith("text/plain")) {
            return false;
        }
        return true;
    }
    if (HttpHeader.ACCEPT_LC.equals(name)
            || HttpHeader.ACCEPT_LANGUAGE_LC.equals(name)
            || HttpHeader.CONTENT_LANGUAGE_LC.equals(name)
            || HttpHeader.REFERER_LC.equals(name)
            || "accept-encoding".equals(name)
            || HttpHeader.ORIGIN_LC.equals(name)) {
        return false;
    }
    return true;
}
 
Example #3
Source File: XMLHttpRequest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @param name header name (MUST be lower-case for performance reasons)
 * @param value header value
 */
private static boolean isPreflightHeader(final String name, final String value) {
    if (HttpHeader.CONTENT_TYPE_LC.equals(name)) {
        final String lcValue = value.toLowerCase(Locale.ROOT);
        if (lcValue.startsWith(FormEncodingType.URL_ENCODED.getName())
            || lcValue.startsWith(FormEncodingType.MULTIPART.getName())
            || lcValue.startsWith(FormEncodingType.TEXT_PLAIN.getName())) {
            return false;
        }
        return true;
    }
    if (HttpHeader.ACCEPT_LC.equals(name)
            || HttpHeader.ACCEPT_LANGUAGE_LC.equals(name)
            || HttpHeader.CONTENT_LANGUAGE_LC.equals(name)
            || HttpHeader.REFERER_LC.equals(name)
            || "accept-encoding".equals(name)
            || HttpHeader.ORIGIN_LC.equals(name)) {
        return false;
    }
    return true;
}
 
Example #4
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 #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 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 #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 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 #7
Source File: XMLHTTPRequest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @param name header name (MUST be lower-case for performance reasons)
 * @param value header value
 */
private static boolean isPreflightHeader(final String name, final String value) {
    if (HttpHeader.CONTENT_TYPE_LC.equals(name)) {
        final String lcValue = value.toLowerCase(Locale.ROOT);
        return !(lcValue.startsWith(FormEncodingType.URL_ENCODED.getName())
            || lcValue.startsWith(FormEncodingType.MULTIPART.getName())
            || lcValue.startsWith(MimeType.TEXT_PLAIN));
    }

    return !(HttpHeader.ACCEPT_LC.equals(name)
            || HttpHeader.ACCEPT_LANGUAGE_LC.equals(name)
            || HttpHeader.CONTENT_LANGUAGE_LC.equals(name)
            || HttpHeader.REFERER_LC.equals(name)
            || HttpHeader.ACCEPT_ENCODING_LC.equals(name)
            || HttpHeader.ORIGIN_LC.equals(name));
}
 
Example #8
Source File: HTMLFormElementTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private void enctypeTest(final boolean html5, final String enctype,
                final String method, final String expectedCntType) throws Exception {
    String html = "";
    if (html5) {
        html += "<!DOCTYPE html>\n";
    }
    html += "<html><head><script>\n"
        + "function test() {\n"
        + "  var f = document.forms[0];\n"
        + "  f.submit();\n"
        + "}\n"
        + "</script></head><body onload='test()'>\n"
        + "<form action='foo.html' ";
    if (enctype != null) {
        html += "enctype='" + enctype + "' ";
    }
    html += "method='" + method + "'>\n"
        + "  <input name='myField' value='some value'>\n"
        + "</form></body></html>";

    getMockWebConnection().setDefaultResponse("<html><title>Response</title></html>");
    final WebDriver driver = loadPage2(html);
    assertTitle(driver, "Response");
    String headerValue = getMockWebConnection().getLastWebRequest().getAdditionalHeaders()
        .get(HttpHeader.CONTENT_TYPE);
    if (headerValue != null && headerValue.startsWith(FormEncodingType.MULTIPART.getName())) {
        // Can't test equality for multipart/form-data as it will have the form:
        // multipart/form-data; boundary=---------------------------42937861433140731107235900
        headerValue = StringUtils.substringBefore(headerValue, ";");
        assertEquals(expectedCntType, headerValue);
    }
    else {
        assertEquals(expectedCntType, headerValue);
    }
}
 
Example #9
Source File: HTMLFormElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the value of the property {@code enctype}.
 * @param enctype the new value
 */
@JsxSetter
public void setEnctype(final String enctype) {
    WebAssert.notNull("encoding", enctype);
    if (getBrowserVersion().hasFeature(JS_FORM_REJECT_INVALID_ENCODING)) {
        if (!FormEncodingType.URL_ENCODED.getName().equals(enctype)
                && !FormEncodingType.MULTIPART.getName().equals(enctype)) {
            throw Context.reportRuntimeError("Cannot set the encoding property to invalid value: '"
                    + enctype + "'");
        }
    }
    getHtmlForm().setEnctypeAttribute(enctype);
}
 
Example #10
Source File: HTMLFormElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the value of the property {@code enctype}.
 * @return the value of this property
 */
@JsxGetter
public String getEnctype() {
    final String encoding = getHtmlForm().getEnctypeAttribute();
    if (!FormEncodingType.URL_ENCODED.getName().equals(encoding)
            && !FormEncodingType.MULTIPART.getName().equals(encoding)
            && !"text/plain".equals(encoding)) {
        return FormEncodingType.URL_ENCODED.getName();
    }
    return encoding;
}
 
Example #11
Source File: HtmlForm2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void formUrlEncodedEncodingTypeTest() 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"
        + "    <button id='myButton' type='submit'>Submit</button>\n"
        + "  </form>\n"
        + "</body></html>";

    final String secondContent
        = "<html><head><title>second</title></head><body>\n"
        + "  <p>hello world</p>\n"
        + "</body></html>";

    getMockWebConnection().setResponse(URL_SECOND, secondContent);

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

    assertEquals(2, getMockWebConnection().getRequestCount());
    assertEquals(URL_SECOND.toString(), getMockWebConnection().getLastWebRequest().getUrl());
    assertEquals(FormEncodingType.URL_ENCODED, getMockWebConnection().getLastWebRequest().getEncodingType());
}
 
Example #12
Source File: HtmlForm2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void formMultipartEncodingTypeTest() 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 type='file' value='file1'>\n"
        + "    <button id='myButton' type='submit'>Submit</button>\n"
        + "  </form>\n"
        + "</body></html>";
    final String secondContent
        = "<html><head><title>second</title></head><body>\n"
        + "  <p>hello world</p>\n"
        + "</body></html>";

    getMockWebConnection().setResponse(URL_SECOND, secondContent);

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

    assertEquals(2, getMockWebConnection().getRequestCount());
    assertEquals(URL_SECOND.toString(), getMockWebConnection().getLastWebRequest().getUrl());
    assertEquals(FormEncodingType.MULTIPART, getMockWebConnection().getLastWebRequest().getEncodingType());
}
 
Example #13
Source File: HtmlUnitRequestBuilderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-14916
public void buildRequestContentTypeWithFormSubmission() {
	webRequest.setEncodingType(FormEncodingType.URL_ENCODED);

	MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

	assertThat(actualRequest.getContentType(), equalTo("application/x-www-form-urlencoded"));
	assertThat(actualRequest.getHeader("Content-Type"),
			equalTo("application/x-www-form-urlencoded;charset=ISO-8859-1"));
}
 
Example #14
Source File: HTMLFormElementTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private void jsEncoding(final String encoding) throws Exception {
    final String html
        = "<html>\n"
        + "<head>\n"
        + "  <script>\n"
        + "  function doTest() {\n"
        + "    try {\n"
        + "      document.forms[0].encoding = '" + encoding + "';\n"
        + "      alert(document.forms[0].encoding);\n"
        + "    } catch(e) { alert('exception'); }\n"
        + "    alert(document.forms[0].enctype);\n"
        + "  }\n"
        + "  </script>\n"
        + "</head>\n"
        + "<body onload='doTest()'>\n"
        + "  <form id='testForm' name='testForm' method='post' action = 'page2.html'>\n"
        + "    <input type='submit' name='submit1' />\n"
        + "  </form>\n"
        + "</body></html>";

    getMockWebConnection().setDefaultResponse("<html><title>Response</title></html>");

    final WebDriver driver = loadPage2(html);
    verifyAlerts(DEFAULT_WAIT_TIME, driver, new String[] {getExpectedAlerts()[0], getExpectedAlerts()[1]});

    driver.findElement(By.name("submit1")).click();
    assertTitle(driver, "Response");
    String headerValue = getMockWebConnection().getLastWebRequest().getAdditionalHeaders()
        .get(HttpHeader.CONTENT_TYPE);
    if (headerValue.startsWith(FormEncodingType.MULTIPART.getName())) {
        // Can't test equality for multipart/form-data as it will have the form:
        // multipart/form-data; boundary=---------------------------42937861433140731107235900
        headerValue = StringUtils.substringBefore(headerValue, ";");
        assertEquals(getExpectedAlerts()[2], headerValue);
    }
    else {
        assertEquals(getExpectedAlerts()[2], headerValue);
    }
}
 
Example #15
Source File: HTMLFormElementTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private void jsEnctype(final String enctype) throws Exception {
    final String html
        = "<html>\n"
        + "<head>\n"
        + "  <script>\n"
        + "  function doTest() {\n"
        + "    try {\n"
        + "      document.forms[0].enctype = '" + enctype + "';\n"
        + "      alert(document.forms[0].enctype);\n"
        + "    } catch(e) { alert('exception'); }\n"
        + "    alert(document.forms[0].encoding);\n"
        + "  }\n"
        + "  </script>\n"
        + "</head>\n"
        + "<body onload='doTest()'>\n"
        + "  <form id='testForm' name='testForm' method='post' action = 'page2.html'>\n"
        + "    <input type='submit' name='submit1' />\n"
        + "  </form>\n"
        + "</body></html>";

    getMockWebConnection().setDefaultResponse("<html><title>Response</title></html>");

    final WebDriver driver = loadPage2(html);
    verifyAlerts(DEFAULT_WAIT_TIME, driver, new String[] {getExpectedAlerts()[0], getExpectedAlerts()[1]});

    driver.findElement(By.name("submit1")).click();
    assertTitle(driver, "Response");
    String headerValue = getMockWebConnection().getLastWebRequest().getAdditionalHeaders()
        .get(HttpHeader.CONTENT_TYPE);

    if (headerValue.startsWith(FormEncodingType.MULTIPART.getName())) {
        // Can't test equality for multipart/form-data as it will have the form:
        // multipart/form-data; boundary=---------------------------42937861433140731107235900
        headerValue = StringUtils.substringBefore(headerValue, ";");
        assertEquals(getExpectedAlerts()[2], headerValue);
    }
    else {
        assertEquals(getExpectedAlerts()[2], headerValue);
    }
}
 
Example #16
Source File: DebuggingWebConnection.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Saves the response content in the temp dir and adds it to the summary page.
 * @param response the response to save
 * @param request the request used to get the response
 * @throws IOException if a problem occurs writing the file
 */
protected void saveResponse(final WebResponse response, final WebRequest request)
    throws IOException {
    counter_++;
    final String extension = chooseExtension(response.getContentType());
    final File file = createFile(request.getUrl(), extension);
    int length = 0;
    try (InputStream input = response.getContentAsStream()) {
        try (OutputStream fos = Files.newOutputStream(file.toPath())) {
            length = IOUtils.copy(input, fos);
        }
        catch (final EOFException e) {
            // ignore
        }
    }

    final URL url = response.getWebRequest().getUrl();
    if (LOG.isInfoEnabled()) {
        LOG.info("Created file " + file.getAbsolutePath() + " for response " + counter_ + ": " + url);
    }

    final StringBuilder bduiler = new StringBuilder();
    bduiler.append("tab[tab.length] = {code: " + response.getStatusCode() + ", ")
            .append("fileName: '" + file.getName() + "', ")
            .append("contentType: '" + response.getContentType() + "', ")
            .append("method: '" + request.getHttpMethod().name() + "', ");
    if (request.getHttpMethod() == HttpMethod.POST && request.getEncodingType() == FormEncodingType.URL_ENCODED) {
        bduiler.append("postParameters: " + nameValueListToJsMap(request.getRequestParameters()) + ", ");
    }
    bduiler.append("url: '" + escapeJSString(url.toString()) + "', ")
            .append("loadTime: " + response.getLoadTime() + ", ")
            .append("responseSize: " + length + ", ")
            .append("responseHeaders: " + nameValueListToJsMap(response.getResponseHeaders()))
            .append("};\n");
    appendToJSFile(bduiler.toString());
}
 
Example #17
Source File: HTMLFormElement.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the value of the property {@code enctype}.
 * @param enctype the new value
 */
@JsxSetter
public void setEnctype(final String enctype) {
    WebAssert.notNull("encoding", enctype);
    if (getBrowserVersion().hasFeature(JS_FORM_REJECT_INVALID_ENCODING)
            && !FormEncodingType.URL_ENCODED.getName().equals(enctype)
            && !FormEncodingType.MULTIPART.getName().equals(enctype)
            && !FormEncodingType.TEXT_PLAIN.getName().equals(enctype)) {
        throw Context.reportRuntimeError("Cannot set the encoding property to invalid value: '" + enctype + "'");
    }
    getHtmlForm().setEnctypeAttribute(enctype);
}
 
Example #18
Source File: HTMLFormElement.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the value of the property {@code enctype}.
 * @return the value of this property
 */
@JsxGetter
public String getEnctype() {
    final String encoding = getHtmlForm().getEnctypeAttribute();
    if (!FormEncodingType.URL_ENCODED.getName().equals(encoding)
            && !FormEncodingType.MULTIPART.getName().equals(encoding)
            && !MimeType.TEXT_PLAIN.equals(encoding)) {
        return FormEncodingType.URL_ENCODED.getName();
    }
    return encoding;
}
 
Example #19
Source File: XMLHttpRequest.java    From htmlunit with Apache License 2.0 5 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())
        && !Undefined.isUndefined(content)) {

        final boolean setEncodingType = webRequest_.getAdditionalHeader(HttpHeader.CONTENT_TYPE) == null;
        if (content instanceof FormData) {
            ((FormData) content).fillRequest(webRequest_);
        }
        else if (content instanceof NativeArrayBufferView) {
            final NativeArrayBufferView view = (NativeArrayBufferView) content;
            webRequest_.setRequestBody(new String(view.getBuffer().getBuffer(), UTF_8));
            if (setEncodingType) {
                webRequest_.setEncodingType(null);
            }
        }
        else if (content instanceof URLSearchParams) {
            ((URLSearchParams) content).fillRequest(webRequest_);
            webRequest_.addHint(HttpHint.IncludeCharsetInContentTypeHeader);
        }
        else {
            final String body = Context.toString(content);
            if (!body.isEmpty()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Setting request body to: " + body);
                }
                webRequest_.setRequestBody(body);
                webRequest_.setCharset(UTF_8);
                if (setEncodingType) {
                    webRequest_.setEncodingType(FormEncodingType.TEXT_PLAIN);
                }
            }
        }
    }
}
 
Example #20
Source File: URLSearchParams.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the specified request with the parameters in this {@code FormData}.
 * @param webRequest the web request to fill
 */
public void fillRequest(final WebRequest webRequest) {
    webRequest.setRequestBody(null);
    webRequest.setEncodingType(FormEncodingType.URL_ENCODED);

    if (params_.size() > 0) {
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (Entry<String, String> entry : params_) {
            params.add(new NameValuePair(entry.getKey(), entry.getValue()));
        }
        webRequest.setRequestParameters(params);
    }
}
 
Example #21
Source File: HtmlUnitRequestBuilderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-14916
public void buildRequestContentTypeWithFormSubmission() {
	webRequest.setEncodingType(FormEncodingType.URL_ENCODED);

	MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

	assertThat(actualRequest.getContentType(), equalTo("application/x-www-form-urlencoded"));
	assertThat(actualRequest.getHeader("Content-Type"),
			equalTo("application/x-www-form-urlencoded;charset=ISO-8859-1"));
}
 
Example #22
Source File: FormData.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the specified request with the parameters in this {@code FormData}.
 * @param webRequest the web request to fill
 */
public void fillRequest(final WebRequest webRequest) {
    webRequest.setEncodingType(FormEncodingType.MULTIPART);
    webRequest.setRequestParameters(requestParameters_);
}
 
Example #23
Source File: FormData.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the specified request with the parameters in this {@code FormData}.
 * @param webRequest the web request to fill
 */
public void fillRequest(final WebRequest webRequest) {
    webRequest.setEncodingType(FormEncodingType.MULTIPART);
    webRequest.setRequestParameters(requestParameters_);
}
 
Example #24
Source File: HtmlForm.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * Gets the request for a submission of this form with the specified SubmittableElement.
 * @param submitElement the element that caused the submit to occur
 * @return the request
 */
public WebRequest getWebRequest(final SubmittableElement submitElement) {
    final HtmlPage htmlPage = (HtmlPage) getPage();
    final List<NameValuePair> parameters = getParameterListForSubmit(submitElement);
    final HttpMethod method;
    final String methodAttribute = getMethodAttribute();
    if ("post".equalsIgnoreCase(methodAttribute)) {
        method = HttpMethod.POST;
    }
    else {
        if (!"get".equalsIgnoreCase(methodAttribute) && StringUtils.isNotBlank(methodAttribute)) {
            notifyIncorrectness("Incorrect submit method >" + getMethodAttribute() + "<. Using >GET<.");
        }
        method = HttpMethod.GET;
    }

    final BrowserVersion browser = getPage().getWebClient().getBrowserVersion();
    String actionUrl = getActionAttribute();
    String anchor = null;
    String queryFromFields = "";
    if (HttpMethod.GET == method) {
        if (actionUrl.contains("#")) {
            anchor = StringUtils.substringAfter(actionUrl, "#");
        }
        final Charset enc = getPage().getCharset();
        queryFromFields =
            URLEncodedUtils.format(Arrays.asList(NameValuePair.toHttpClient(parameters)), enc);

        // action may already contain some query parameters: they have to be removed
        actionUrl = StringUtils.substringBefore(actionUrl, "#");
        actionUrl = StringUtils.substringBefore(actionUrl, "?");
        parameters.clear(); // parameters have been added to query
    }
    URL url;
    try {
        if (actionUrl.isEmpty()) {
            url = WebClient.expandUrl(htmlPage.getUrl(), actionUrl);
        }
        else {
            url = htmlPage.getFullyQualifiedUrl(actionUrl);
        }

        if (!queryFromFields.isEmpty()) {
            url = UrlUtils.getUrlWithNewQuery(url, queryFromFields);
        }

        if (HttpMethod.GET == method && browser.hasFeature(FORM_SUBMISSION_URL_WITHOUT_HASH)
                && WebClient.URL_ABOUT_BLANK != url) {
            url = UrlUtils.getUrlWithNewRef(url, null);
        }
        else if (HttpMethod.POST == method
                && browser.hasFeature(FORM_SUBMISSION_URL_WITHOUT_HASH)
                && WebClient.URL_ABOUT_BLANK != url
                && StringUtils.isEmpty(actionUrl)) {
            url = UrlUtils.getUrlWithNewRef(url, null);
        }
        else if (anchor != null
                && WebClient.URL_ABOUT_BLANK != url) {
            url = UrlUtils.getUrlWithNewRef(url, anchor);
        }
    }
    catch (final MalformedURLException e) {
        throw new IllegalArgumentException("Not a valid url: " + actionUrl);
    }

    final WebRequest request = new WebRequest(url, method);
    request.setAdditionalHeader(HttpHeader.ACCEPT, browser.getHtmlAcceptHeader());
    request.setAdditionalHeader(HttpHeader.ACCEPT_ENCODING, "gzip, deflate");
    request.setRequestParameters(parameters);
    if (HttpMethod.POST == method) {
        request.setEncodingType(FormEncodingType.getInstance(getEnctypeAttribute()));
    }
    request.setCharset(getSubmitCharset());

    String referer = htmlPage.getUrl().toExternalForm();
    request.setAdditionalHeader(HttpHeader.REFERER, referer);

    if (HttpMethod.POST == method
            && browser.hasFeature(FORM_SUBMISSION_HEADER_ORIGIN)) {
        referer = StringUtils.stripEnd(referer, "/");
        request.setAdditionalHeader(HttpHeader.ORIGIN, referer);
    }
    if (HttpMethod.POST == method
            && browser.hasFeature(FORM_SUBMISSION_HEADER_CACHE_CONTROL_MAX_AGE)) {
        request.setAdditionalHeader(HttpHeader.CACHE_CONTROL, "max-age=0");
    }
    if (browser.hasFeature(FORM_SUBMISSION_HEADER_CACHE_CONTROL_NO_CACHE)) {
        request.setAdditionalHeader(HttpHeader.CACHE_CONTROL, "no-cache");
    }

    return request;
}