下面列出了io.reactivex.MaybeOnSubscribe#com.gargoylesoftware.htmlunit.HttpMethod 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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);
}
}
}
}
}
/**
* @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());
}
/**
* @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));
}
}
/**
* @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());
}
/**
* @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());
}
/**
* @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());
}
/**
* @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());
}
/**
* @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());
}
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());
}
/**
* @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());
}
/**
* 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);
}
/**
* 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);
}
}
}
}
/**
* 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);
}
}
}
}
}
/**
* 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());
}
/**
* 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());
}
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());
}
@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());
}
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 [email protected]${mutant} \
// --cookie "${cookie}" --cookie-jar "${cookie}" \
// -w @curl-format.txt \
// -s ${CODE_DEFENDER_URL}/multiplayergame
browser.getPage(attackRequest);
}
@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"));
}
}
@Test
public void buildRequestContentLength() {
String content = "some content that has length";
webRequest.setHttpMethod(HttpMethod.POST);
webRequest.setRequestBody(content);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getContentLength(), equalTo(content.length()));
}
@Test
@SuppressWarnings("deprecation")
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));
}
@Test
public void buildRequestMethods() {
for (HttpMethod expectedMethod : HttpMethod.values()) {
webRequest.setHttpMethod(expectedMethod);
String actualMethod = requestBuilder.buildRequest(servletContext).getMethod();
assertThat(actualMethod, equalTo(expectedMethod.name()));
}
}
@Test
public void buildRequestReader() throws Exception {
String expectedBody = "request body";
webRequest.setHttpMethod(HttpMethod.POST);
webRequest.setRequestBody(expectedBody);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(IOUtils.toString(actualRequest.getReader()), equalTo(expectedBody));
}
@Test
public void buildRequestContentLength() {
String content = "some content that has length";
webRequest.setHttpMethod(HttpMethod.POST);
webRequest.setRequestBody(content);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getContentLength(), equalTo(content.length()));
}
@Test
@SuppressWarnings("deprecation")
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));
}
@Test
public void buildRequestReader() throws Exception {
String expectedBody = "request body";
webRequest.setHttpMethod(HttpMethod.POST);
webRequest.setRequestBody(expectedBody);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(IOUtils.toString(actualRequest.getReader()), equalTo(expectedBody));
}
/**
* 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);
}
}
}
}
}
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;
}
/**
* 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());
}
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;
}