How to use getContentString method of org.openqa.selenium.remote.http.HttpRequest class

Best Selenium code snippet using org.openqa.selenium.remote.http.HttpRequest.getContentString

Source:HttpClientTestBase.java Github

copy

Full Screen

...84 public void shouldSendSimpleQueryParameters() throws Exception {85 HttpRequest request = new HttpRequest(GET, "/query");86 request.addQueryParameter("cheese", "cheddar");87 HttpResponse response = getQueryParameterResponse(request);88 Map<String, Object> values = new Json().toType(response.getContentString(), MAP_TYPE);89 assertEquals(ImmutableList.of("cheddar"), values.get("cheese"));90 }91 @Test92 public void shouldEncodeParameterNamesAndValues() throws Exception {93 HttpRequest request = new HttpRequest(GET, "/query");94 request.addQueryParameter("cheese type", "tasty cheese");95 HttpResponse response = getQueryParameterResponse(request);96 Map<String, Object> values = new Json().toType(response.getContentString(), MAP_TYPE);97 assertEquals(ImmutableList.of("tasty cheese"), values.get("cheese type"));98 }99 @Test100 public void canAddMoreThanOneQueryParameter() throws Exception {101 HttpRequest request = new HttpRequest(GET, "/query");102 request.addQueryParameter("cheese", "cheddar");103 request.addQueryParameter("cheese", "gouda");104 request.addQueryParameter("vegetable", "peas");105 HttpResponse response = getQueryParameterResponse(request);106 Map<String, Object> values = new Json().toType(response.getContentString(), MAP_TYPE);107 assertEquals(ImmutableList.of("cheddar", "gouda"), values.get("cheese"));108 assertEquals(ImmutableList.of("peas"), values.get("vegetable"));109 }110 @Test111 public void shouldAllowUrlsWithSchemesToBeUsed() throws Exception {112 Server server = new Server(PortProber.findFreePort());113 ServletContextHandler handler = new ServletContextHandler();114 handler.setContextPath("");115 class Canned extends HttpServlet {116 @Override117 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {118 try (PrintWriter writer = resp.getWriter()) {119 writer.append("Hello, World!");120 }121 }122 }123 ServletHolder holder = new ServletHolder(new Canned());124 handler.addServlet(holder, "/*");125 server.setHandler(handler);126 server.start();127 try {128 // This is a terrible choice of URL129 HttpClient client = createFactory().createClient(new URL("http://example.com"));130 URI uri = server.getURI();131 HttpRequest request = new HttpRequest(132 GET,133 String.format("http://%s:%s/hello", uri.getHost(), uri.getPort()));134 HttpResponse response = client.execute(request);135 assertEquals("Hello, World!", response.getContentString());136 } finally {137 server.stop();138 }139 }140 @Test141 public void shouldIncludeAUserAgentHeader() throws Exception {142 HttpResponse response = executeWithinServer(143 new HttpRequest(GET, "/foo"),144 new HttpServlet() {145 @Override146 protected void doGet(HttpServletRequest req, HttpServletResponse resp)147 throws IOException {148 try (Writer writer = resp.getWriter()) {149 writer.write(req.getHeader("user-agent"));150 }151 }152 });153 String label = new BuildInfo().getReleaseLabel();154 Platform platform = Platform.getCurrent();155 Platform family = platform.family() == null ? platform : platform.family();156 assertEquals(157 response.getContentString(),158 String.format(159 "selenium/%s (java %s)",160 label,161 family.toString().toLowerCase()),162 response.getContentString());163 }164 private HttpResponse getResponseWithHeaders(final Multimap<String, String> headers)165 throws Exception {166 return executeWithinServer(167 new HttpRequest(GET, "/foo"),168 new HttpServlet() {169 @Override170 protected void doGet(HttpServletRequest req, HttpServletResponse resp) {171 headers.forEach(resp::addHeader);172 resp.setContentLengthLong(0);173 }174 });175 }176 private HttpResponse getQueryParameterResponse(HttpRequest request) throws Exception {...

Full Screen

Full Screen

Source:ProtocolConverterTest.java Github

copy

Full Screen

...76 HttpResponse resp = new HttpResponse();77 handler.handle(w3cRequest, resp);78 assertEquals(MediaType.JSON_UTF_8, MediaType.parse(resp.getHeader("Content-type")));79 assertEquals(HttpURLConnection.HTTP_OK, resp.getStatus());80 Map<String, Object> parsed = json.toType(resp.getContentString(), MAP_TYPE);81 assertNull(parsed.toString(), parsed.get("sessionId"));82 assertTrue(parsed.toString(), parsed.containsKey("value"));83 assertNull(parsed.toString(), parsed.get("value"));84 }85 @Test86 public void shouldAliasAComplexCommand() throws IOException {87 SessionId sessionId = new SessionId("1234567");88 // Downstream is JSON, upstream is W3C. This way we can force "isDisplayed" to become JS89 // execution.90 SessionCodec handler = new ProtocolConverter(91 new URL("http://example.com/wd/hub"),92 new JsonHttpCommandCodec(),93 new JsonHttpResponseCodec(),94 new W3CHttpCommandCodec(),95 new W3CHttpResponseCodec()) {96 @Override97 protected HttpResponse makeRequest(HttpRequest request) {98 assertEquals(String.format("/session/%s/execute/sync", sessionId), request.getUri());99 Map<String, Object> params = json.toType(request.getContentString(), MAP_TYPE);100 assertEquals(101 ImmutableList.of(102 ImmutableMap.of(W3C.getEncodedElementKey(), "4567890")),103 params.get("args"));104 HttpResponse response = new HttpResponse();105 response.setHeader("Content-Type", MediaType.JSON_UTF_8.toString());106 response.setHeader("Cache-Control", "none");107 Map<String, Object> obj = ImmutableMap.of(108 "sessionId", sessionId.toString(),109 "status", 0,110 "value", true);111 String payload = json.toJson(obj);112 response.setContent(payload.getBytes(UTF_8));113 return response;114 }115 };116 Command command = new Command(117 sessionId,118 DriverCommand.IS_ELEMENT_DISPLAYED,119 ImmutableMap.of("id", "4567890"));120 HttpRequest w3cRequest = new JsonHttpCommandCodec().encode(command);121 HttpResponse resp = new HttpResponse();122 handler.handle(w3cRequest, resp);123 assertEquals(MediaType.JSON_UTF_8, MediaType.parse(resp.getHeader("Content-type")));124 assertEquals(HttpURLConnection.HTTP_OK, resp.getStatus());125 Map<String, Object> parsed = json.toType(resp.getContentString(), MAP_TYPE);126 assertNull(parsed.get("sessionId"));127 assertTrue(parsed.containsKey("value"));128 assertEquals(true, parsed.get("value"));129 }130 @Test131 public void shouldConvertAnException() throws IOException {132 // Json upstream, w3c downstream133 SessionId sessionId = new SessionId("1234567");134 SessionCodec handler = new ProtocolConverter(135 new URL("http://example.com/wd/hub"),136 new W3CHttpCommandCodec(),137 new W3CHttpResponseCodec(),138 new JsonHttpCommandCodec(),139 new JsonHttpResponseCodec()) {140 @Override141 protected HttpResponse makeRequest(HttpRequest request) {142 HttpResponse response = new HttpResponse();143 response.setHeader("Content-Type", MediaType.JSON_UTF_8.toString());144 response.setHeader("Cache-Control", "none");145 String payload = new Json().toJson(146 ImmutableMap.of(147 "sessionId", sessionId.toString(),148 "status", UNHANDLED_ERROR,149 "value", new WebDriverException("I love cheese and peas")));150 response.setContent(payload.getBytes(UTF_8));151 response.setStatus(HTTP_INTERNAL_ERROR);152 return response;153 }154 };155 Command command = new Command(156 sessionId,157 DriverCommand.GET,158 ImmutableMap.of("url", "http://example.com/cheese"));159 HttpRequest w3cRequest = new W3CHttpCommandCodec().encode(command);160 HttpResponse resp = new HttpResponse();161 handler.handle(w3cRequest, resp);162 assertEquals(MediaType.JSON_UTF_8, MediaType.parse(resp.getHeader("Content-type")));163 assertEquals(HTTP_INTERNAL_ERROR, resp.getStatus());164 Map<String, Object> parsed = json.toType(resp.getContentString(), MAP_TYPE);165 assertNull(parsed.get("sessionId"));166 assertTrue(parsed.containsKey("value"));167 @SuppressWarnings("unchecked") Map<String, Object> value =168 (Map<String, Object>) parsed.get("value");169 System.out.println("value = " + value.keySet());170 assertEquals("unknown error", value.get("error"));171 assertTrue(((String) value.get("message")).startsWith("I love cheese and peas"));172 }173}...

Full Screen

Full Screen

Source:ProtocolHandshake.java Github

copy

Full Screen

...80 // Ignore the content type. It may not have been set. Strictly speaking we're not following the81 // W3C spec properly. Oh well.82 Map<?, ?> blob;83 try {84 blob = new Json().toType(response.getContentString(), Map.class);85 } catch (JsonException e) {86 throw new WebDriverException(87 "Unable to parse remote response: " + response.getContentString());88 }89 InitialHandshakeResponse initialResponse = new InitialHandshakeResponse(90 time,91 response.getStatus(),92 blob);93 return Stream.of(94 new JsonWireProtocolResponse().getResponseFunction(),95 new Gecko013ProtocolResponse().getResponseFunction(),96 new W3CHandshakeResponse().getResponseFunction())97 .map(func -> func.apply(initialResponse))98 .filter(Optional::isPresent)99 .map(Optional::get)100 .findFirst();101 }...

Full Screen

Full Screen

Source:Docker.java Github

copy

Full Screen

...46 try {47 HttpResponse resp = client.execute(req);48 if (resp.getStatus() < 200 && resp.getStatus() > 200) {49 try {50 Object obj = JSON.toType(resp.getContentString(), Object.class);51 if (obj instanceof Map) {52 Map<?, ?> map = (Map<?, ?>) obj;53 String message = map.get("message") instanceof String ?54 (String) map.get("message") :55 resp.getContentString();56 throw new RuntimeException(message);57 }58 throw new RuntimeException(resp.getContentString());59 } catch (JsonException e) {60 throw new RuntimeException(resp.getContentString());61 }62 }63 return resp;64 } catch (IOException e) {65 throw new UncheckedIOException(e);66 }67 };68 }69 public Image pull(String name, String tag) {70 Objects.requireNonNull(name);71 Objects.requireNonNull(tag);72 findImage(new ImageNamePredicate(name, tag));73 LOG.info(String.format("Pulling %s:%s", name, tag));74 HttpRequest request = new HttpRequest(POST, "/images/create");75 request.addQueryParameter("fromImage", name);76 request.addQueryParameter("tag", tag);77 client.apply(request);78 LOG.info(String.format("Pull of %s:%s complete", name, tag));79 return findImage(new ImageNamePredicate(name, tag))80 .orElseThrow(() -> new DockerException(81 String.format("Cannot find image matching: %s:%s", name, tag)));82 }83 public List<Image> listImages() {84 LOG.fine("Listing images");85 HttpResponse response = client.apply(new HttpRequest(GET, "/images/json"));86 List<ImageSummary> images =87 JSON.toType(response.getContentString(), new TypeToken<List<ImageSummary>>() {}.getType());88 return images.stream()89 .map(Image::new)90 .collect(toImmutableList());91 }92 public Optional<Image> findImage(Predicate<Image> filter) {93 Objects.requireNonNull(filter);94 LOG.fine("Finding image: " + filter);95 return listImages().stream()96 .filter(filter)97 .findFirst();98 }99 public Container create(ContainerInfo info) {100 StringBuilder json = new StringBuilder();101 try (JsonOutput output = JSON.newOutput(json)) {102 output.setPrettyPrint(false);103 output.write(info);104 }105 LOG.info("Creating container: " + json);106 HttpRequest request = new HttpRequest(POST, "/containers/create");107 request.setContent(json.toString().getBytes(UTF_8));108 HttpResponse response = client.apply(request);109 Map<String, Object> toRead = JSON.toType(response.getContentString(), MAP_TYPE);110 return new Container(client, new ContainerId((String) toRead.get("Id")));111 }112}...

Full Screen

Full Screen

Source:Grid1HeartbeatTest.java Github

copy

Full Screen

...46 HttpRequest request = new HttpRequest(GET, heartbeatUrl.toString());47 HttpClient client = HttpClient.Factory.createDefault().createClient(hub.getUrl());48 HttpResponse response = client.execute(request);49 assertEquals(200, response.getStatus());50 assertEquals("Hub : Not Registered", response.getContentString());51 }52 @Test53 public void testIsRegistered() throws Exception {54 // register a selenium 155 SelfRegisteringRemote selenium1 =56 GridTestHelper.getRemoteWithoutCapabilities(hub.getUrl(), GridRole.NODE);57 selenium1.addBrowser(GridTestHelper.getDefaultBrowserCapability(), 1);58 selenium1.setRemoteServer(new SeleniumServer(selenium1.getConfiguration()));59 selenium1.startRemoteServer();60 selenium1.sendRegistrationRequest();61 RegistryTestHelper.waitForNode(hub.getRegistry(), 1);62 // Check that the node is registered with the hub.63 URL heartbeatUrl =64 new URL(String.format("http://%s:%s/heartbeat?host=%s&port=%s", hub.getConfiguration().host, hub65 .getConfiguration().port, selenium1.getConfiguration().host, selenium166 .getConfiguration().port));67 HttpRequest request = new HttpRequest(GET, heartbeatUrl.toString());68 HttpClient client = HttpClient.Factory.createDefault().createClient(hub.getUrl());69 HttpResponse response = client.execute(request);70 assertEquals(200, response.getStatus());71 assertEquals("Hub : OK", response.getContentString());72 }73 @After74 public void teardown() {75 hub.stop();76 }77}...

Full Screen

Full Screen

Source:ExceptionHandlerTest.java Github

copy

Full Screen

...35 Exception e = new NoSuchSessionException("This does not exist");36 HttpResponse response = new HttpResponse();37 new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session"), response);38 assertEquals(HTTP_INTERNAL_ERROR, response.getStatus());39 Map<String, Object> err = new Json().toType(response.getContentString(), MAP_TYPE);40 assertEquals(ErrorCodes.NO_SUCH_SESSION, ((Number) err.get("status")).intValue());41 }42 @Test43 public void shouldSetErrorCodeForW3cSpec() {44 Exception e = new NoAlertPresentException("This does not exist");45 HttpResponse response = new HttpResponse();46 new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session"), response);47 Map<String, Object> err = new Json().toType(response.getContentString(), MAP_TYPE);48 Map<?, ?> value = (Map<?, ?>) err.get("value");49 assertEquals(value.toString(), "no such alert", value.get("error"));50 }51 @Test52 public void shouldUnwrapAnExecutionException() {53 Exception noSession = new SessionNotCreatedException("This does not exist");54 Exception e = new ExecutionException(noSession);55 HttpResponse response = new HttpResponse();56 new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session"), response);57 Map<String, Object> err = new Json().toType(response.getContentString(), MAP_TYPE);58 Map<?, ?> value = (Map<?, ?>) err.get("value");59 assertEquals(ErrorCodes.SESSION_NOT_CREATED, ((Number) err.get("status")).intValue());60 assertEquals("session not created", value.get("error"));61 }62}...

Full Screen

Full Screen

Source:DisplayHelpHandlerTest.java Github

copy

Full Screen

...40 HttpRequest request = new HttpRequest(GET, "/");41 HttpResponse response = new HttpResponse();42 handler.execute(request, response);43 assertThat(response.getStatus()).isEqualTo(HTTP_OK);44 String body = response.getContentString();45 assertThat(body).isNotNull().contains(46 "Whoops! The URL specified routes to this help page.",47 "\"type\": \"Standalone\"",48 "\"consoleLink\": \"\\u002fwd\\u002fhub\"");49 }50 @Test51 public void testGetHelpPageAsset() throws IOException {52 HttpResponse response = new HttpResponse();53 handler.execute(new HttpRequest(GET, "/assets/displayhelpservlet.css"), response);54 assertThat(response.getStatus()).isEqualTo(HTTP_OK);55 assertThat(response.getContentString()).isNotNull().contains("#help-heading #logo");56 }57 @Test58 public void testNoSuchAsset() throws IOException {59 HttpResponse response = new HttpResponse();60 handler.execute(new HttpRequest(GET, "/assets/foo.bar"), response);61 assertThat(response.getStatus()).isEqualTo(HTTP_NOT_FOUND);62 }63 @Test64 public void testAccessRoot() throws IOException {65 HttpResponse response = new HttpResponse();66 handler.execute(new HttpRequest(GET, "/"), response);67 assertThat(response.getStatus()).isEqualTo(HTTP_OK);68 }69}...

Full Screen

Full Screen

Source:HttpUtil.java Github

copy

Full Screen

...43 // Create HttpClient object with the URL44 HttpClient client = HttpClient.Factory.createDefault().createClient(url); 45 HttpResponse response = client.execute(request); // Execute the request46 // Created a JSONObject from the API response, assuming REST API and the response is json string47 JSONObject resultJson = new JSONObject(response.getContentString()); 48 return resultJson; 49 } catch (MalformedURLException e) { 50 e.printStackTrace();51 } catch (IOException e) {52 e.printStackTrace();53 } 54 return null;55 }56}...

Full Screen

Full Screen

getContentString

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.http.HttpRequest;2import org.openqa.selenium.remote.http.HttpResponse;3public class GetContentString {4 public static void main(String[] args) {5 HttpRequest request = new HttpRequest("GET", "/test");6 request.setContentString("This is a test");7 HttpResponse response = new HttpResponse();8 response.setContentString(request.getContentString());9 System.out.println(response.getContentString());10 }11}

Full Screen

Full Screen

getContentString

Using AI Code Generation

copy

Full Screen

1public static String getContentString(HttpRequest request){2 String contentString = null;3 if(request.getContent() != null){4 contentString = new String(request.getContent().readAllBytes(), StandardCharsets.UTF_8);5 }6 return contentString;7}8public static String getContentString(HttpResponse response){9 String contentString = null;10 if(response.getContent() != null){11 contentString = new String(response.getContent().readAllBytes(), StandardCharsets.UTF_8);12 }13 return contentString;14}15public static String getContentString(HttpResponse response){16 String contentString = null;17 if(response.getContent() != null){18 contentString = new String(response.getContent().readAllBytes(), StandardCharsets.UTF_8);19 }20 return contentString;21}22public static String getContentString(HttpResponse response){23 String contentString = null;24 if(response.getContent() != null){25 contentString = new String(response.getContent().readAllBytes(), StandardCharsets.UTF_8);26 }27 return contentString;28}29public static String getContentString(HttpResponse response){30 String contentString = null;31 if(response.getContent() != null){32 contentString = new String(response.getContent().readAllBytes(), StandardCharsets.UTF_8);33 }34 return contentString;35}36public static String getContentString(HttpResponse response){37 String contentString = null;38 if(response.getContent() != null){39 contentString = new String(response.getContent().readAllBytes(), StandardCharsets.UTF_8);40 }41 return contentString;42}43public static String getContentString(HttpResponse response){44 String contentString = null;45 if(response.getContent() != null){46 contentString = new String(response.getContent().readAllBytes(), StandardCharsets.UTF_8);47 }48 return contentString;49}50public static String getContentString(HttpResponse response){51 String contentString = null;52 if(response.getContent() !=

Full Screen

Full Screen

getContentString

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.http.HttpRequest;2public class HttpReq {3 public static void main(String[] args) {4 HttpRequest request = new HttpRequest("GET", "/session");5 request.addHeader("Accept", "application/json");6 request.addHeader("Content-Type", "application/json");7 request.addHeader("User-Agent", "Selenium/3.141.59 (java windows)");8 String content = request.getContentString();9 System.out.println(content);10 }11}12User-Agent: Selenium/3.141.59 (java windows)13import org.openqa.selenium.remote.http.HttpRequest;14public class HttpReq {15 public static void main(String[] args) {16 HttpRequest request = new HttpRequest("GET", "/session");17 request.addHeader("Accept", "application/json");18 request.addHeader("Content-Type", "application/json");19 request.addHeader("User-Agent", "Selenium/3.141.59 (java windows)");20 byte[] content = request.getContent();21 System.out.println(new String(content));22 }23}24User-Agent: Selenium/3.141.59 (java windows)

Full Screen

Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful