下面列出了怎么用org.openqa.selenium.remote.http.HttpMethod的API类实例代码及写法,或者点击链接到github查看源代码。
public BufferedImage takeScreenshotEntirePageUsingChromeCommand() {
//should use devicePixelRatio by default as chrome command executor makes screenshot account for that
Object devicePixelRatio = executeJsScript(DEVICE_PIXEL_RATIO);
this.devicePixelRatio = devicePixelRatio instanceof Double ? (Double) devicePixelRatio : (Long) devicePixelRatio * 1.0;
defineCustomCommand("sendCommand", new CommandInfo("/session/:sessionId/chromium/send_command_and_get_result", HttpMethod.POST));
int verticalIterations = (int) Math.ceil(((double) this.getDocHeight()) / this.getViewportHeight());
for (int j = 0; j < verticalIterations; j++) {
this.scrollTo(0, j * this.getViewportHeight());
wait(betweenScrollTimeout);
}
Object metrics = this.evaluate(FileUtil.getJsScript(ALL_METRICS));
this.sendCommand("Emulation.setDeviceMetricsOverride", metrics);
wait(beforeShootCondition,beforeShootTimeout);
Object result = this.sendCommand("Page.captureScreenshot", ImmutableMap.of("format", "png", "fromSurface", true));
this.sendCommand("Emulation.clearDeviceMetricsOverride", ImmutableMap.of());
return decodeBase64EncodedPng((String) ((Map<String, ?>) result).get("data"));
}
public BufferedImage takeScreenshotEntirePageUsingGeckoDriver() {
// Check geckodriver version (>= 0.24.0 is requried)
String version = (String) ((RemoteWebDriver) driver).getCapabilities().getCapability("moz:geckodriverVersion");
if (version == null || Version.valueOf(version).satisfies("<0.24.0")) {
return takeScreenshotEntirePageDefault();
}
defineCustomCommand("mozFullPageScreenshot", new CommandInfo("/session/:sessionId/moz/screenshot/full", HttpMethod.GET));
Object result = this.executeCustomCommand("mozFullPageScreenshot");
String base64EncodedPng;
if (result instanceof String) {
base64EncodedPng = (String) result;
} else if (result instanceof byte[]) {
base64EncodedPng = new String((byte[]) result);
} else {
throw new RuntimeException(String.format("Unexpected result for /moz/screenshot/full command: %s",
result == null ? "null" : result.getClass().getName() + "instance"));
}
return decodeBase64EncodedPng(base64EncodedPng);
}
/**
* Returns whether this instance matches the provided HTTP request.
*
* @param method The request method.
* @param parts The parsed request path segments.
* @return Whether this instance matches the request.
*/
boolean isFor(HttpMethod method, ImmutableList<String> parts) {
if (!this.method.equals(method)) {
return false;
}
if (parts.size() != this.pathSegments.size()) {
return false;
}
for (int i = 0; i < parts.size(); ++i) {
String reqPart = parts.get(i);
String specPart = pathSegments.get(i);
if (!(specPart.startsWith(":") || specPart.equals(reqPart))) {
return false;
}
}
return true;
}
@Override
public String create(Page page) {
try {
byte[] data = new Json()
.toJson(ImmutableMap.of("content", page.toString()))
.getBytes(UTF_8);
HttpClient client = HttpClient.Factory.createDefault().createClient(new URL(whereIs("/")));
HttpRequest request = new HttpRequest(HttpMethod.POST, "/common/createPage");
request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());
request.setContent(bytes(data));
HttpResponse response = client.execute(request);
return string(response);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
static HttpRequest asRequest(HttpExchange exchange) {
HttpRequest request = new HttpRequest(
HttpMethod.valueOf(exchange.getRequestMethod()),
exchange.getRequestURI().getPath());
String query = exchange.getRequestURI().getQuery();
if (query != null) {
Arrays.stream(query.split("&"))
.map(q -> {
int i = q.indexOf("=");
if (i == -1) {
return new AbstractMap.SimpleImmutableEntry<>(q, "");
}
return new AbstractMap.SimpleImmutableEntry<>(q.substring(0, i), q.substring(i + 1));
})
.forEach(entry -> request.addQueryParameter(entry.getKey(), entry.getValue()));
}
exchange.getRequestHeaders().forEach((name, values) -> values.forEach(value -> request.addHeader(name, value)));
request.setContent(memoize(exchange::getRequestBody));
return request;
}
public AllHandlers(NewSessionPipeline pipeline, ActiveSessions allSessions) {
this.allSessions = Require.nonNull("Active sessions", allSessions);
this.json = new Json();
this.additionalHandlers = ImmutableMap.of(
HttpMethod.DELETE, ImmutableList.of(),
HttpMethod.GET, ImmutableList.of(
handler("/session/{sessionId}/log/types",
params -> new GetLogTypes(json, allSessions.get(new SessionId(params.get("sessionId"))))),
handler("/sessions", params -> new GetAllSessions(allSessions, json)),
handler("/status", params -> new Status(json))
),
HttpMethod.POST, ImmutableList.of(
handler("/session", params -> new BeginSession(pipeline, allSessions, json)),
handler("/session/{sessionId}/file",
params -> new UploadFile(json, allSessions.get(new SessionId(params.get("sessionId"))))),
handler("/session/{sessionId}/log",
params -> new GetLogsOfType(json, allSessions.get(new SessionId(params.get("sessionId"))))),
handler("/session/{sessionId}/se/file",
params -> new UploadFile(json, allSessions.get(new SessionId(params.get("sessionId")))))
));
}
@Test
public void shouldWriteABase64EncodedZippedFileToDiskAndKeepName() throws Exception {
ActiveSession session = mock(ActiveSession.class);
when(session.getId()).thenReturn(new SessionId("1234567"));
when(session.getFileSystem()).thenReturn(tempFs);
when(session.getDownstreamDialect()).thenReturn(Dialect.OSS);
File tempFile = touch(null, "foo");
String encoded = Zip.zip(tempFile);
UploadFile uploadFile = new UploadFile(new Json(), session);
Map<String, Object> args = ImmutableMap.of("file", encoded);
HttpRequest request = new HttpRequest(HttpMethod.POST, "/session/%d/se/file");
request.setContent(asJson(args));
HttpResponse response = uploadFile.execute(request);
Response res = new Json().toType(string(response), Response.class);
String path = (String) res.getValue();
assertTrue(new File(path).exists());
assertTrue(path.endsWith(tempFile.getName()));
}
private static Map<String, CommandInfo> buildChromiumCommandMappings(String vendorKeyword) {
String sessionPrefix = "/session/:sessionId/";
String chromiumPrefix = sessionPrefix + "chromium";
String vendorPrefix = sessionPrefix + vendorKeyword;
HashMap<String, CommandInfo> mappings = new HashMap<>();
mappings.put(ChromiumDriverCommand.LAUNCH_APP,
new CommandInfo(chromiumPrefix + "/launch_app", HttpMethod.POST));
String networkConditions = chromiumPrefix + "/network_conditions";
mappings.put(ChromiumDriverCommand.GET_NETWORK_CONDITIONS,
new CommandInfo(networkConditions, HttpMethod.GET));
mappings.put(ChromiumDriverCommand.SET_NETWORK_CONDITIONS,
new CommandInfo(networkConditions, HttpMethod.POST));
mappings.put(ChromiumDriverCommand.DELETE_NETWORK_CONDITIONS,
new CommandInfo(networkConditions, HttpMethod.DELETE));
mappings.put( ChromiumDriverCommand.EXECUTE_CDP_COMMAND,
new CommandInfo(vendorPrefix + "/cdp/execute", HttpMethod.POST));
// Cast / Media Router APIs
String cast = vendorPrefix + "/cast";
mappings.put(ChromiumDriverCommand.GET_CAST_SINKS,
new CommandInfo(cast + "/get_sinks", HttpMethod.GET));
mappings.put(ChromiumDriverCommand.SET_CAST_SINK_TO_USE,
new CommandInfo(cast + "/set_sink_to_use", HttpMethod.POST));
mappings.put(ChromiumDriverCommand.START_CAST_TAB_MIRRORING,
new CommandInfo(cast + "/start_tab_mirroring", HttpMethod.POST));
mappings.put(ChromiumDriverCommand.GET_CAST_ISSUE_MESSAGE,
new CommandInfo(cast + "/get_issue_message", HttpMethod.GET));
mappings.put(ChromiumDriverCommand.STOP_CASTING,
new CommandInfo(cast + "/stop_casting", HttpMethod.POST));
mappings.put(ChromiumDriverCommand.SET_PERMISSION,
new CommandInfo(sessionPrefix + "/permissions", HttpMethod.POST));
return unmodifiableMap(mappings);
}
private Optional<Result> createSession(HttpClient client, InputStream newSessionBlob, long size) {
// Create the http request and send it
HttpRequest request = new HttpRequest(HttpMethod.POST, "/session");
HttpResponse response;
long start = System.currentTimeMillis();
request.setHeader(CONTENT_LENGTH, String.valueOf(size));
request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());
request.setContent(() -> newSessionBlob);
response = client.execute(request);
long time = System.currentTimeMillis() - start;
// Ignore the content type. It may not have been set. Strictly speaking we're not following the
// W3C spec properly. Oh well.
Map<?, ?> blob;
try {
blob = new Json().toType(string(response), Map.class);
} catch (JsonException e) {
throw new WebDriverException(
"Unable to parse remote response: " + string(response), e);
}
InitialHandshakeResponse initialResponse = new InitialHandshakeResponse(
time,
response.getStatus(),
blob);
return Stream.of(
new W3CHandshakeResponse().getResponseFunction(),
new JsonWireProtocolResponse().getResponseFunction())
.map(func -> func.apply(initialResponse))
.filter(Objects::nonNull)
.findFirst();
}
@Override
public HttpRequest encode(Command command) {
String name = aliases.getOrDefault(command.getName(), command.getName());
CommandSpec spec = nameToSpec.get(name);
if (spec == null) {
throw new UnsupportedCommandException(command.getName());
}
Map<String, ?> parameters = amendParameters(command.getName(), command.getParameters());
String uri = buildUri(name, command.getSessionId(), parameters, spec);
HttpRequest request = new HttpRequest(spec.method, uri);
if (HttpMethod.POST == spec.method) {
String content = json.toJson(parameters);
byte[] data = content.getBytes(UTF_8);
request.setHeader(CONTENT_LENGTH, String.valueOf(data.length));
request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());
request.setContent(bytes(data));
}
if (HttpMethod.GET == spec.method) {
request.setHeader(CACHE_CONTROL, "no-cache");
}
return request;
}
@Test
public void manifestHasCorrectMimeType() throws IOException {
String url = server.whereIs("html5/test.appcache");
HttpClient.Factory factory = HttpClient.Factory.createDefault();
HttpClient client = factory.createClient(new URL(url));
HttpResponse response = client.execute(new HttpRequest(HttpMethod.GET, url));
System.out.printf("Content for %s was %s\n", url, string(response));
assertTrue(StreamSupport.stream(response.getHeaders("Content-Type").spliterator(), false)
.anyMatch(header -> header.contains(APPCACHE_MIME_TYPE)));
}
@Override
public String create(Page page) {
try {
byte[] data = new Json().toJson(singletonMap("content", page.toString())).getBytes(UTF_8);
HttpClient client = HttpClient.Factory.createDefault().createClient(new URL(whereIs("/")));
HttpRequest request = new HttpRequest(HttpMethod.POST, "/common/createPage");
request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());
request.setContent(bytes(data));
HttpResponse response = client.execute(request);
return string(response);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
@Override
public void stop() {
// Try and kill the running session. Both W3C and OSS use the same quit endpoint
try {
HttpRequest request = new HttpRequest(HttpMethod.DELETE, "/session/" + getId());
execute(request);
} catch (UncheckedIOException e) {
// This is fine.
}
service.stop();
}
private HttpRequest createRequest(io.netty.handler.codec.http.HttpRequest nettyRequest) {
HttpRequest req = new HttpRequest(
HttpMethod.valueOf(nettyRequest.method().name()),
nettyRequest.uri());
nettyRequest.headers().entries().stream()
.filter(entry -> entry.getKey() != null)
.forEach(entry -> req.addHeader(entry.getKey(), entry.getValue()));
return req;
}
@Test
public void shouldForwardRequestsToEndPoint() {
HttpHandler handler = new ReverseProxyHandler(tracer, factory.createClient(server.url));
HttpRequest req = new HttpRequest(HttpMethod.GET, "/ok");
req.addHeader("X-Cheese", "Cake");
handler.execute(req);
// HTTP headers are case insensitive. This is how the HttpUrlConnection likes to encode things
assertEquals("Cake", server.lastRequest.getHeader("x-cheese"));
}
public Server() throws IOException {
int port = PortProber.findFreePort();
String address = new NetworkUtils().getPrivateLocalAddress();
url = new URL("http", address, port, "/ok");
server = HttpServer.create(new InetSocketAddress(address, port), 0);
server.createContext("/ok", ex -> {
lastRequest = new HttpRequest(
HttpMethod.valueOf(ex.getRequestMethod()),
ex.getRequestURI().getPath());
Headers headers = ex.getRequestHeaders();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
for (String value : entry.getValue()) {
lastRequest.addHeader(entry.getKey().toLowerCase(), value);
}
}
try (InputStream in = ex.getRequestBody()) {
lastRequest.setContent(bytes(ByteStreams.toByteArray(in)));
}
byte[] payload = "I like cheese".getBytes(UTF_8);
ex.sendResponseHeaders(HTTP_OK, payload.length);
try (OutputStream out = ex.getResponseBody()) {
out.write(payload);
}
});
server.start();
}
private static Map<String, Object> getValueForPostRequest(URL serverUrl) throws Exception {
String url = serverUrl + "/logs";
HttpClient.Factory factory = HttpClient.Factory.createDefault();
HttpClient client = factory.createClient(new URL(url));
HttpResponse response = client.execute(new HttpRequest(HttpMethod.POST, url));
Map<String, Object> map = new Json().toType(string(response), MAP_TYPE);
return (Map<String, Object>) map.get("value");
}
@Test
public void shouldThrowAnExceptionIfMoreThanOneFileIsSent() throws Exception {
ActiveSession session = mock(ActiveSession.class);
when(session.getId()).thenReturn(new SessionId("1234567"));
when(session.getFileSystem()).thenReturn(tempFs);
when(session.getDownstreamDialect()).thenReturn(Dialect.OSS);
File baseDir = Files.createTempDir();
touch(baseDir, "example");
touch(baseDir, "unwanted");
String encoded = Zip.zip(baseDir);
UploadFile uploadFile = new UploadFile(new Json(), session);
Map<String, Object> args = ImmutableMap.of("file", encoded);
HttpRequest request = new HttpRequest(HttpMethod.POST, "/session/%d/se/file");
request.setContent(asJson(args));
HttpResponse response = uploadFile.execute(request);
try {
new ErrorHandler(false).throwIfResponseFailed(
new Json().toType(string(response), Response.class),
100);
fail("Should not get this far");
} catch (WebDriverException ignored) {
// Expected
}
}
@Test
public void shouldSetErrorCodeForJsonWireProtocol() {
Exception e = new NoSuchSessionException("This does not exist");
HttpResponse response = new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session"));
assertEquals(HTTP_INTERNAL_ERROR, response.getStatus());
Map<String, Object> err = new Json().toType(string(response), MAP_TYPE);
assertEquals(ErrorCodes.NO_SUCH_SESSION, ((Number) err.get("status")).intValue());
}
@Test
public void shouldSetErrorCodeForW3cSpec() {
Exception e = new NoAlertPresentException("This does not exist");
HttpResponse response = new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session"));
Map<String, Object> err = new Json().toType(string(response), MAP_TYPE);
Map<?, ?> value = (Map<?, ?>) err.get("value");
assertEquals(value.toString(), "no such alert", value.get("error"));
}
@Test
public void shouldUnwrapAnExecutionException() {
Exception noSession = new SessionNotCreatedException("This does not exist");
Exception e = new ExecutionException(noSession);
HttpResponse response = new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session"));
Map<String, Object> err = new Json().toType(string(response), MAP_TYPE);
Map<?, ?> value = (Map<?, ?>) err.get("value");
assertEquals(ErrorCodes.SESSION_NOT_CREATED, ((Number) err.get("status")).intValue());
assertEquals("session not created", value.get("error"));
}
public CommandInfo(String url, HttpMethod method) {
this.url = url;
this.method = method;
}
HttpMethod getMethod() {
return method;
}
protected static CommandSpec delete(String path) {
return new CommandSpec(HttpMethod.DELETE, path);
}
protected static CommandSpec get(String path) {
return new CommandSpec(HttpMethod.GET, path);
}
protected static CommandSpec post(String path) {
return new CommandSpec(HttpMethod.POST, path);
}
private CommandSpec(HttpMethod method, String path) {
this.method = Require.nonNull("HTTP method", method);
this.path = path;
this.pathSegments = ImmutableList.copyOf(PATH_SPLITTER.split(path));
}
public CommandInfo(String url, HttpMethod method) {
this.url = url;
this.method = method;
}
HttpMethod getMethod() {
return method;
}
@Test
public void verifyRequestPostData() {
devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));
final RequestId[] requestIds = new RequestId[1];
devTools.addListener(requestWillBeSent(), requestWillBeSent -> {
Assert.assertNotNull(requestWillBeSent);
if (requestWillBeSent.getRequest().getMethod().equalsIgnoreCase(HttpMethod.POST.name())) {
requestIds[0] = requestWillBeSent.getRequestId();
}
});
driver.get(appServer.whereIs("postForm.html"));
driver.findElement(By.xpath("/html/body/form/input")).click();
Assert.assertNotNull(devTools.send(getRequestPostData(requestIds[0])));
}