Java Code Examples for com.gargoylesoftware.htmlunit.util.NameValuePair
The following examples show how to use
com.gargoylesoftware.htmlunit.util.NameValuePair.
These examples are extracted from open source projects.
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 Project: HtmlUnit-Android Author: null-dev File: HttpWebConnection.java License: Apache License 2.0 | 6 votes |
private static Charset getCharset(final Charset charset, final List<NameValuePair> pairs) { for (final NameValuePair pair : pairs) { if (pair instanceof KeyDataPair) { final KeyDataPair pairWithFile = (KeyDataPair) pair; if (pairWithFile.getData() == null && pairWithFile.getFile() != null) { final String fileName = pairWithFile.getFile().getName(); for (int i = 0; i < fileName.length(); i++) { if (fileName.codePointAt(i) > 127) { return charset; } } } } } return null; }
Example #2
Source Project: htmlunit Author: HtmlUnit File: HtmlForm2Test.java License: Apache License 2.0 | 6 votes |
private void submitParams(final String controls) throws Exception { final String html = "<html><head><title>foo</title></head><body>\n" + "<form id='form1' method='post'>\n" + controls + "</form></body></html>"; final WebDriver driver = loadPage2(html); driver.findElement(new ById("mySubmit")).click(); final List<NameValuePair> requestedParams = getMockWebConnection().getLastWebRequest().getRequestParameters(); Collections.sort(requestedParams, Comparator.comparing(NameValuePair::getName)); assertEquals(getExpectedAlerts().length, requestedParams.size()); for (int i = 0; i < requestedParams.size(); i++) { assertEquals(getExpectedAlerts()[i], requestedParams.get(i).getName() + '#' + requestedParams.get(i).getValue()); } }
Example #3
Source Project: htmlunit Author: HtmlUnit File: HtmlImage2Test.java License: Apache License 2.0 | 6 votes |
private void isDisplayed(final String src) throws Exception { try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img")) { final byte[] directBytes = IOUtils.toByteArray(is); final URL urlImage = new URL(URL_FIRST, "img.jpg"); final List<NameValuePair> emptyList = Collections.emptyList(); getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "image/jpg", emptyList); getMockWebConnection().setDefaultResponse("Error: not found", 404, "Not Found", MimeType.TEXT_HTML); } final String html = "<html><head><title>Page A</title></head>\n" + "<body>\n" + " <img id='myImg' " + src + " >\n" + "</body></html>"; final WebDriver driver = loadPage2(html); final boolean displayed = driver.findElement(By.id("myImg")).isDisplayed(); assertEquals(Boolean.parseBoolean(getExpectedAlerts()[0]), displayed); }
Example #4
Source Project: htmlunit Author: HtmlUnit File: CookieManagerTest.java License: Apache License 2.0 | 6 votes |
/** * A cookie set with document.cookie without path applies only for the current path * and overrides cookie previously set for this path. * @throws Exception if the test fails */ @Test @Alerts("first=new") public void cookieSetFromJSWithoutPathUsesCurrentLocation() throws Exception { final List<NameValuePair> responseHeader1 = new ArrayList<>(); responseHeader1.add(new NameValuePair("Set-Cookie", "first=1")); final String html = "<html>\n" + "<head></head>\n" + "<body><script>\n" + " document.cookie = 'first=new';\n" + " location.replace('/a/b/-');\n" + "</script></body>\n" + "</html>"; getMockWebConnection().setDefaultResponse(HTML_ALERT_COOKIE); final URL firstUrl = new URL(URL_FIRST, "/a/b"); getMockWebConnection().setResponse(firstUrl, html, 200, "Ok", MimeType.TEXT_HTML, responseHeader1); loadPageWithAlerts2(firstUrl); }
Example #5
Source Project: htmlunit Author: HtmlUnit File: FormData.java License: Apache License 2.0 | 6 votes |
/** * @param name the name of the field to check * @return the first value found for the give name */ @JsxFunction({CHROME, FF, FF68, FF60}) public String get(final String name) { if (StringUtils.isEmpty(name)) { return null; } final Iterator<NameValuePair> iter = requestParameters_.iterator(); while (iter.hasNext()) { final NameValuePair pair = iter.next(); if (name.equals(pair.getName())) { return pair.getValue(); } } return null; }
Example #6
Source Project: htmlunit Author: HtmlUnit File: FormData.java License: Apache License 2.0 | 6 votes |
/** * @param name the name of the field to check * @return the first value found for the give name */ @JsxFunction({CHROME, FF, FF68, FF60}) public Scriptable getAll(final String name) { if (StringUtils.isEmpty(name)) { return Context.getCurrentContext().newArray(this, 0); } final List<Object> values = new ArrayList<>(); final Iterator<NameValuePair> iter = requestParameters_.iterator(); while (iter.hasNext()) { final NameValuePair pair = iter.next(); if (name.equals(pair.getName())) { values.add(pair.getValue()); } } final Object[] stringValues = values.toArray(new Object[values.size()]); return Context.getCurrentContext().newArray(this, stringValues); }
Example #7
Source Project: htmlunit Author: HtmlUnit File: FormData.java License: Apache License 2.0 | 6 votes |
/** * @param name the name of the field to check * @return true if the name exists */ @JsxFunction({CHROME, FF, FF68, FF60}) public boolean has(final String name) { if (StringUtils.isEmpty(name)) { return false; } final Iterator<NameValuePair> iter = requestParameters_.iterator(); while (iter.hasNext()) { final NameValuePair pair = iter.next(); if (name.equals(pair.getName())) { return true; } } return false; }
Example #8
Source Project: htmlunit Author: HtmlUnit File: HtmlPageTest.java License: Apache License 2.0 | 6 votes |
/** * Test auto-refresh from a response header. * @throws Exception if the test fails */ @Test public void refresh_HttpResponseHeader() throws Exception { final String firstContent = "<html><head><title>first</title>\n" + "</head><body></body></html>"; final String secondContent = "<html><head><title>second</title></head><body></body></html>"; final WebClient client = getWebClient(); final MockWebConnection webConnection = new MockWebConnection(); webConnection.setResponse(URL_FIRST, firstContent, 200, "OK", MimeType.TEXT_HTML, Collections .singletonList(new NameValuePair("Refresh", "2;URL=" + URL_SECOND))); webConnection.setResponse(URL_SECOND, secondContent); client.setWebConnection(webConnection); final HtmlPage page = client.getPage(URL_FIRST); assertEquals("second", page.getTitleText()); }
Example #9
Source Project: htmlunit Author: HtmlUnit File: WebClient3Test.java License: Apache License 2.0 | 6 votes |
/** * @throws Exception if an error occurs */ @Test @Alerts({"Executed", "later"}) // TODO [IE]ERRORPAGE real IE displays own error page if response is to small public void execJavascriptOnErrorPages() throws Exception { final String errorHtml = "<html>\n" + "<head>\n" + "</head>\n" + "<body>\n" + "<script type='text/javascript'>\n" + " alert('Executed');\n" + " setTimeout(\"alert('later')\", 10);\n" + "</script>\n" + "</body></html>\n"; final MockWebConnection conn = getMockWebConnection(); conn.setResponse(URL_FIRST, errorHtml, 404, "Not Found", MimeType.TEXT_HTML, new ArrayList<NameValuePair>()); loadPageWithAlerts2(URL_FIRST, 42); }
Example #10
Source Project: HtmlUnit-Android Author: null-dev File: XMLHttpRequest.java License: Apache License 2.0 | 6 votes |
/** * Returns the labels and values of all the HTTP headers. * @return the labels and values of all the HTTP headers */ @JsxFunction public String getAllResponseHeaders() { if (state_ == UNSENT || state_ == OPENED) { return ""; } if (webResponse_ != null) { final StringBuilder builder = new StringBuilder(); for (final NameValuePair header : webResponse_.getResponseHeaders()) { builder.append(header.getName()).append(": ").append(header.getValue()).append("\r\n"); } if (getBrowserVersion().hasFeature(XHR_ALL_RESPONSE_HEADERS_APPEND_CRLF)) { builder.append("\r\n"); } return builder.toString(); } LOG.error("XMLHttpRequest.getAllResponseHeaders() was called without a response available (readyState: " + state_ + ")."); return null; }
Example #11
Source Project: htmlunit Author: HtmlUnit File: WebClient6Test.java License: Apache License 2.0 | 6 votes |
/** * Regression test for bug 3035155. * Bug was fixes in HttpClient 4.1. * @throws Exception if an error occurs */ @Test public void redirect302UrlsInQuery() throws Exception { final String html = "<html><body><a href='redirect.html'>redirect</a></body></html>"; final URL url = new URL(URL_FIRST, "page2.html"); getMockWebConnection().setResponse(url, html); final List<NameValuePair> headers = new ArrayList<>(); headers.add(new NameValuePair("Location", "/page2.html?param=http%3A//somwhere.org")); getMockWebConnection().setDefaultResponse("", 302, "Found", null, headers); final WebDriver driver = loadPage2(html); driver.findElement(By.tagName("a")).click(); assertEquals(url + "?param=http%3A//somwhere.org", driver.getCurrentUrl()); }
Example #12
Source Project: htmlunit Author: HtmlUnit File: HtmlFileInput.java License: Apache License 2.0 | 6 votes |
/** * {@inheritDoc} */ @Override public NameValuePair[] getSubmitNameValuePairs() { if (files_ == null || files_.length == 0) { return new NameValuePair[] {new KeyDataPair(getNameAttribute(), null, null, null, (Charset) null)}; } final List<NameValuePair> list = new ArrayList<>(); for (File file : files_) { String contentType; if (contentType_ == null) { contentType = getPage().getWebClient().getBrowserVersion().getUploadMimeType(file); if (StringUtils.isEmpty(contentType)) { contentType = MimeType.APPLICATION_OCTET_STREAM; } } else { contentType = contentType_; } final Charset charset = getPage().getCharset(); final KeyDataPair keyDataPair = new KeyDataPair(getNameAttribute(), file, null, contentType, charset); keyDataPair.setData(data_); list.add(keyDataPair); } return list.toArray(new NameValuePair[list.size()]); }
Example #13
Source Project: htmlunit Author: HtmlUnit File: CookieManagerTest.java License: Apache License 2.0 | 6 votes |
/** * @throws Exception if the test fails */ @Test @Alerts("first=1") public void cookie2() throws Exception { final List<NameValuePair> responseHeader1 = new ArrayList<>(); responseHeader1.add(new NameValuePair("Set-Cookie", "first=1")); getMockWebConnection().setResponse(URL_FIRST, HTML_ALERT_COOKIE, 200, "OK", MimeType.TEXT_HTML, responseHeader1); loadPageWithAlerts2(URL_FIRST); final List<NameValuePair> responseHeader2 = new ArrayList<>(); responseHeader2.add(new NameValuePair("Set-Cookie", "second=2")); getMockWebConnection().setResponse(URL_FIRST, HTML_ALERT_COOKIE, 200, "OK", MimeType.TEXT_HTML, responseHeader2); setExpectedAlerts("first=1; second=2"); loadPageWithAlerts2(URL_FIRST); }
Example #14
Source Project: htmlunit Author: HtmlUnit File: HtmlSubmitInputTest.java License: Apache License 2.0 | 6 votes |
/** * @throws Exception if the test fails */ @Test public void submit() throws Exception { final String html = "<html><head><title>foo</title></head><body>\n" + "<form id='form1' method='post'>\n" + "<input type='submit' name='aButton' value='foo'/>\n" + "<input type='suBMit' name='button' value='foo'/>\n" + "<input type='submit' name='anotherButton' value='foo'/>\n" + "</form></body></html>"; final WebDriver driver = loadPageWithAlerts2(html); final WebElement button = driver.findElement(By.name("button")); button.click(); assertTitle(driver, "foo"); assertEquals(Collections.singletonList(new NameValuePair("button", "foo")), getMockWebConnection().getLastParameters()); }
Example #15
Source Project: htmlunit Author: HtmlUnit File: WebClientTest.java License: Apache License 2.0 | 6 votes |
private void redirection_AdditionalHeadersMaintained(final int statusCode) throws Exception { final WebClient client = getWebClient(); final MockWebConnection conn = new MockWebConnection(); client.setWebConnection(conn); final List<NameValuePair> headers = asList(new NameValuePair("Location", URL_SECOND.toString())); conn.setResponse(URL_FIRST, "", statusCode, "", MimeType.TEXT_HTML, headers); conn.setResponse(URL_SECOND, "<html><body>abc</body></html>"); final WebRequest request = new WebRequest(URL_FIRST); request.setAdditionalHeader("foo", "bar"); client.getPage(request); assertEquals(URL_SECOND, conn.getLastWebRequest().getUrl()); assertEquals("bar", conn.getLastAdditionalHeaders().get("foo")); }
Example #16
Source Project: HtmlUnit-Android Author: null-dev File: WebClient.java License: Apache License 2.0 | 6 votes |
private WebResponse makeWebResponseForDataUrl(final WebRequest webRequest) throws IOException { final URL url = webRequest.getUrl(); final List<NameValuePair> responseHeaders = new ArrayList<>(); final DataURLConnection connection; try { connection = new DataURLConnection(url); } catch (final DecoderException e) { throw new IOException(e.getMessage()); } responseHeaders.add(new NameValuePair(HttpHeader.CONTENT_TYPE_LC, connection.getMediaType() + ";charset=" + connection.getCharset())); try (InputStream is = connection.getInputStream()) { final DownloadedContent downloadedContent = HttpWebConnection.downloadContent(is, getOptions().getMaxInMemory()); final WebResponseData data = new WebResponseData(downloadedContent, 200, "OK", responseHeaders); return new WebResponse(data, url, webRequest.getHttpMethod(), 0); } }
Example #17
Source Project: jenkins-test-harness Author: jenkinsci File: JenkinsRule.java License: MIT License | 6 votes |
private List<NameValuePair> extractHeaders(HttpURLConnection conn) { List<NameValuePair> headers = new ArrayList<NameValuePair>(); Set<Map.Entry<String,List<String>>> headerFields = conn.getHeaderFields().entrySet(); for (Map.Entry<String,List<String>> headerField : headerFields) { String name = headerField.getKey(); if (name != null) { // Yes, the header name can be null. List<String> values = headerField.getValue(); for (String value : values) { if (value != null) { headers.add(new NameValuePair(name, value)); } } } } return headers; }
Example #18
Source Project: spring-analysis-note Author: Vip-Augus File: HtmlUnitRequestBuilder.java License: MIT License | 5 votes |
private void params(MockHttpServletRequest request, UriComponents uriComponents) { uriComponents.getQueryParams().forEach((name, values) -> { String urlDecodedName = urlDecode(name); values.forEach(value -> { value = (value != null ? urlDecode(value) : ""); request.addParameter(urlDecodedName, value); }); }); for (NameValuePair param : this.webRequest.getRequestParameters()) { request.addParameter(param.getName(), param.getValue()); } }
Example #19
Source Project: htmlunit Author: HtmlUnit File: HTMLImageElementTest.java License: Apache License 2.0 | 5 votes |
/** * @throws Exception if an error occurs */ @Test @Alerts({"done;onload;", "2"}) public void img_download_onloadAfter() throws Exception { try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img")) { final byte[] directBytes = IOUtils.toByteArray(is); final URL urlImage = new URL(URL_FIRST, "img.jpg"); final List<NameValuePair> emptyList = Collections.emptyList(); getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "image/jpg", emptyList); } final String html = "<html><body>\n" + "<script>\n" + " var i = new Image();\n" + " i.src = 'img.jpg';\n" + " document.title += 'done;';\n" + " i.onload = function() { document.title += 'onload;'; };\n" + "</script></body></html>"; final int count = getMockWebConnection().getRequestCount(); final WebDriver driver = getWebDriver(); if (driver instanceof HtmlUnitDriver) { ((HtmlUnitDriver) driver).setDownloadImages(true); } loadPage2(html); assertTitle(driver, getExpectedAlerts()[0]); assertEquals(Integer.parseInt(getExpectedAlerts()[1]), getMockWebConnection().getRequestCount() - count); assertEquals(URL_FIRST + "img.jpg", getMockWebConnection().getLastWebRequest().getUrl()); }
Example #20
Source Project: htmlunit Author: HtmlUnit File: HTMLImageElementTest.java License: Apache License 2.0 | 5 votes |
/** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = {"true", "true", "true", "true"}, IE = {"false", "false", "false", "true"}) public void complete() throws Exception { try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img")) { final byte[] directBytes = IOUtils.toByteArray(is); final URL urlImage = new URL(URL_SECOND, "img.jpg"); final List<NameValuePair> emptyList = Collections.emptyList(); getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "image/jpg", emptyList); getMockWebConnection().setDefaultResponse("Test"); } final String html = "<html><head>\n" + "<script>\n" + " function showInfo(imageId) {\n" + " var img = document.getElementById(imageId);\n" + " alert(img.complete);\n" + " }\n" + " function test() {\n" + " showInfo('myImage1');\n" + " showInfo('myImage2');\n" + " showInfo('myImage3');\n" + " showInfo('myImage4');\n" + " }\n" + "</script>\n" + "</head><body onload='test()'>\n" + " <img id='myImage1' >\n" + " <img id='myImage2' src=''>\n" + " <img id='myImage3' src='" + URL_SECOND + "'>\n" + " <img id='myImage4' src='" + URL_SECOND + "img.jpg'>\n" + "</body></html>"; final WebDriver driver = getWebDriver(); if (driver instanceof HtmlUnitDriver) { ((HtmlUnitDriver) driver).setDownloadImages(true); } loadPageWithAlerts2(html); }
Example #21
Source Project: htmlunit Author: HtmlUnit File: CookieManagerTest.java License: Apache License 2.0 | 5 votes |
/** * @throws Exception if the test fails */ @Test @Alerts("key1=; key2=") public void emptyCookie() throws Exception { final List<NameValuePair> responseHeader = new ArrayList<>(); responseHeader.add(new NameValuePair("Set-Cookie", "key1=")); responseHeader.add(new NameValuePair("Set-Cookie", "key2=")); getMockWebConnection().setDefaultResponse(HTML_ALERT_COOKIE, 200, "OK", MimeType.TEXT_HTML, responseHeader); loadPageWithAlerts2(URL_FIRST); }
Example #22
Source Project: CodeDefenders Author: CodeDefenders File: DoubleEquivalenceSubmissionTest.java License: GNU Lesser General Public License v3.0 | 5 votes |
public void defend(int gameId, String test) throws FailingHttpStatusCodeException, IOException { WebRequest defendRequest = new WebRequest(new URL("http://localhost:8080" + Paths.BATTLEGROUND_GAME), HttpMethod.POST); // curl -X POST \ // --data "formType=createTest&gameId=${gameId}" \ // --data-urlencode [email protected]${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 #23
Source Project: java-technology-stack Author: codeEngraver File: HtmlUnitRequestBuilder.java License: MIT License | 5 votes |
private void params(MockHttpServletRequest request, UriComponents uriComponents) { uriComponents.getQueryParams().forEach((name, values) -> { String urlDecodedName = urlDecode(name); values.forEach(value -> { value = (value != null ? urlDecode(value) : ""); request.addParameter(urlDecodedName, value); }); }); for (NameValuePair param : this.webRequest.getRequestParameters()) { request.addParameter(param.getName(), param.getValue()); } }
Example #24
Source Project: htmlunit Author: HtmlUnit File: HTMLIFrameElement3Test.java License: Apache License 2.0 | 5 votes |
/** * @throws Exception if the test fails */ @Test @Alerts({"loaded", "[object HTMLDocument]"}) public void csp_SelfDifferentPath() throws Exception { retrictByHeader( new NameValuePair(HttpHeader.CONTENT_SECURIRY_POLICY, "frame-ancestors 'self';"), new URL(URL_FIRST, "/path2/content.html")); }
Example #25
Source Project: java-technology-stack Author: codeEngraver File: HtmlUnitRequestBuilderTests.java License: MIT License | 5 votes |
@Test public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithSingleRequestParam() { webRequest.setRequestParameters(asList(new NameValuePair("name", "value"))); MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); assertThat(actualRequest.getParameterMap().size(), equalTo(1)); assertThat(actualRequest.getParameter("name"), equalTo("value")); }
Example #26
Source Project: java-technology-stack Author: codeEngraver File: HtmlUnitRequestBuilderTests.java License: MIT License | 5 votes |
@Test public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithSingleRequestParamWithNullValue() { webRequest.setRequestParameters(asList(new NameValuePair("name", null))); MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); assertThat(actualRequest.getParameterMap().size(), equalTo(1)); assertThat(actualRequest.getParameter("name"), nullValue()); }
Example #27
Source Project: java-technology-stack Author: codeEngraver File: HtmlUnitRequestBuilderTests.java License: MIT License | 5 votes |
@Test public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithSingleRequestParamWithValueSetToSpace() { webRequest.setRequestParameters(asList(new NameValuePair("name", " "))); MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); assertThat(actualRequest.getParameterMap().size(), equalTo(1)); assertThat(actualRequest.getParameter("name"), equalTo(" ")); }
Example #28
Source Project: HtmlUnit-Android Author: null-dev File: MockWebConnection.java License: Apache License 2.0 | 5 votes |
private static RawResponseData buildRawResponseData(final String content, Charset charset, final int statusCode, final String statusMessage, final String contentType, final List<NameValuePair> headers) { if (charset == null) { charset = ISO_8859_1; } return new RawResponseData(content, charset, statusCode, statusMessage, contentType, headers); }
Example #29
Source Project: htmlunit Author: HtmlUnit File: HtmlImageInputTest.java License: Apache License 2.0 | 5 votes |
/** * @throws Exception if the test fails */ @Test @Alerts("§§URL§§abcd/img.gif") public void lineBreaksInUrl() throws Exception { try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-gif.img")) { final byte[] directBytes = IOUtils.toByteArray(is); final URL urlImage = new URL(URL_SECOND, "abcd/img.gif"); final List<NameValuePair> emptyList = Collections.emptyList(); getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "image/gif", emptyList); } final String html = "<html><head>\n" + "<script>\n" + " function test() {\n" + " var input = document.getElementById('myInput');\n" + " alert(input.src);\n" + " }\n" + "</script>\n" + "</head>\n" + "<body onload='test()'>\n" + " <input id='myInput' type='image' src='" + URL_SECOND + "a\rb\nc\r\nd/img.gif'>\n" + "</body>\n" + "</html>"; expandExpectedAlertsVariables(URL_SECOND); loadPageWithAlerts2(html); }
Example #30
Source Project: htmlunit Author: HtmlUnit File: WebResponse.java License: Apache License 2.0 | 5 votes |
/** * Returns the value of the specified response header. * @param headerName the name of the header whose value is to be returned * @return the header value, {@code null} if no response header exists with this name */ public String getResponseHeaderValue(final String headerName) { for (final NameValuePair pair : responseData_.getResponseHeaders()) { if (pair.getName().equalsIgnoreCase(headerName)) { return pair.getValue(); } } return null; }