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

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

Source:HttpClientTestBase.java Github

copy

Full Screen

...65 public void responseShouldCaptureASingleHeader() {66 HashMultimap<String, String> headers = HashMultimap.create();67 headers.put("Cake", "Delicious");68 HttpResponse response = getResponseWithHeaders(headers);69 String value = response.getHeader("Cake");70 assertThat(value).isEqualTo("Delicious");71 }72 /**73 * The HTTP Spec that it should be74 * <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">safe to combine them75 * </a>, but things like the <a href="https://www.ietf.org/rfc/rfc2109.txt">cookie spec</a> make76 * this hard (notably when a legal value may contain a comma).77 */78 @Test79 public void responseShouldKeepMultipleHeadersSeparate() {80 HashMultimap<String, String> headers = HashMultimap.create();81 headers.put("Cheese", "Cheddar");82 headers.put("Cheese", "Brie, Gouda");83 HttpResponse response = getResponseWithHeaders(headers);84 List<String> values = StreamSupport85 .stream(response.getHeaders("Cheese").spliterator(), false)86 .collect(toList());87 assertThat(values).contains("Cheddar");88 assertThat(values).contains("Brie, Gouda");89 }90 @Test91 public void shouldAddUrlParameters() {92 HttpRequest request = new HttpRequest(GET, "/query");93 String value = request.getQueryParameter("cheese");94 assertThat(value).isNull();95 request.addQueryParameter("cheese", "brie");96 value = request.getQueryParameter("cheese");97 assertThat(value).isEqualTo("brie");98 }99 @Test100 public void shouldSendSimpleQueryParameters() {101 HttpRequest request = new HttpRequest(GET, "/query");102 request.addQueryParameter("cheese", "cheddar");103 HttpResponse response = getQueryParameterResponse(request);104 Map<String, Object> values = new Json().toType(string(response), MAP_TYPE);105 assertThat(values).containsEntry("cheese", singletonList("cheddar"));106 }107 @Test108 public void shouldEncodeParameterNamesAndValues() {109 HttpRequest request = new HttpRequest(GET, "/query");110 request.addQueryParameter("cheese type", "tasty cheese");111 HttpResponse response = getQueryParameterResponse(request);112 Map<String, Object> values = new Json().toType(string(response), MAP_TYPE);113 assertThat(values).containsEntry("cheese type", singletonList("tasty cheese"));114 }115 @Test116 public void canAddMoreThanOneQueryParameter() {117 HttpRequest request = new HttpRequest(GET, "/query");118 request.addQueryParameter("cheese", "cheddar");119 request.addQueryParameter("cheese", "gouda");120 request.addQueryParameter("vegetable", "peas");121 HttpResponse response = getQueryParameterResponse(request);122 Map<String, Object> values = new Json().toType(string(response), MAP_TYPE);123 assertThat(values).containsEntry("cheese", Arrays.asList("cheddar", "gouda"));124 assertThat(values).containsEntry("vegetable", singletonList("peas"));125 }126 @Test127 public void shouldAllowUrlsWithSchemesToBeUsed() throws Exception {128 delegate = req -> new HttpResponse().setContent(Contents.utf8String("Hello, World!"));129 // This is a terrible choice of URL130 try (HttpClient client = createFactory().createClient(new URL("http://example.com"))) {131 URI uri = URI.create(server.whereIs("/"));132 HttpRequest request =133 new HttpRequest(GET, String.format("http://%s:%s/hello", uri.getHost(), uri.getPort()));134 HttpResponse response = client.execute(request);135 assertThat(string(response)).isEqualTo("Hello, World!");136 }137 }138 @Test139 public void shouldIncludeAUserAgentHeader() {140 HttpResponse response = executeWithinServer(141 new HttpRequest(GET, "/foo"),142 req -> new HttpResponse().setContent(Contents.utf8String(req.getHeader("user-agent"))));143 String label = new BuildInfo().getReleaseLabel();144 Platform platform = Platform.getCurrent();145 Platform family = platform.family() == null ? platform : platform.family();146 assertThat(string(response)).isEqualTo(String.format(147 "selenium/%s (java %s)",148 label,149 family.toString().toLowerCase()));150 }151 @Test152 public void shouldAllowConfigurationOfRequestTimeout() {153 assertThatExceptionOfType(TimeoutException.class)154 .isThrownBy(() -> executeWithinServer(155 new HttpRequest(GET, "/foo"),156 req -> {157 try {158 Thread.sleep(1000);159 } catch (InterruptedException e) {160 e.printStackTrace();161 }162 return new HttpResponse().setContent(Contents.utf8String(req.getHeader("user-agent")));163 },164 ClientConfig.defaultConfig().readTimeout(Duration.ofMillis(500))));165 }166 private HttpResponse getResponseWithHeaders(final Multimap<String, String> headers) {167 return executeWithinServer(168 new HttpRequest(GET, "/foo"),169 req -> {170 HttpResponse resp = new HttpResponse();171 headers.forEach(resp::addHeader);172 return resp;173 });174 }175 private HttpResponse getQueryParameterResponse(HttpRequest request) {176 return executeWithinServer(...

Full Screen

Full Screen

Source:JettyServerTest.java Github

copy

Full Screen

...51 HttpResponse response = client.execute(new HttpRequest(GET, "/status"));52 // Although we don't expect the server to be ready, we do expect the request to succeed.53 assertEquals(HTTP_OK, response.getStatus());54 // And we expect the content to be UTF-8 encoded JSON.55 assertEquals(MediaType.JSON_UTF_8, MediaType.parse(response.getHeader("Content-Type")));56 }57 @Test58 public void shouldAllowAHandlerToBeRegistered() {59 Server<?> server = new JettyServer(60 emptyOptions,61 get("/cheese").to(() -> req -> new HttpResponse().setContent(utf8String("cheddar"))));62 server.start();63 URL url = server.getUrl();64 HttpClient client = HttpClient.Factory.createDefault().createClient(url);65 HttpResponse response = client.execute(new HttpRequest(GET, "/cheese"));66 assertEquals("cheddar", string(response));67 }68 @Test69 public void exceptionsThrownByHandlersAreConvertedToAProperPayload() {70 Server<?> server = new JettyServer(71 emptyOptions,72 req -> {73 throw new UnableToSetCookieException("Yowza");74 });75 server.start();76 URL url = server.getUrl();77 HttpClient client = HttpClient.Factory.createDefault().createClient(url);78 HttpResponse response = client.execute(new HttpRequest(GET, "/status"));79 assertThat(response.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR);80 Throwable thrown = null;81 try {82 thrown = ErrorCodec.createDefault().decode(new Json().toType(string(response), MAP_TYPE));83 } catch (IllegalArgumentException ignored) {84 fail("Apparently the command succeeded" + string(response));85 }86 assertThat(thrown).isInstanceOf(UnableToSetCookieException.class);87 assertThat(thrown.getMessage()).startsWith("Yowza");88 }89 @Test90 public void shouldDisableAllowOrigin() {91 // TODO: Server setup92 Server<?> server = new JettyServer(emptyOptions, req -> new HttpResponse()).start();93 // TODO: Client setup94 URL url = server.getUrl();95 HttpClient client = HttpClient.Factory.createDefault().createClient(url);96 HttpRequest request = new HttpRequest(DELETE, "/session");97 String exampleUrl = "http://www.example.com";98 request.setHeader("Origin", exampleUrl);99 request.setHeader("Accept", "*/*");100 HttpResponse response = client.execute(request);101 // TODO: Assertion102 assertEquals("Access-Control-Allow-Credentials should be null", null,103 response.getHeader("Access-Control-Allow-Credentials"));104 assertEquals("Access-Control-Allow-Origin should be null",105 null,106 response.getHeader("Access-Control-Allow-Origin"));107 }108 @Test109 public void shouldAllowCORS() {110 // TODO: Server setup111 Config cfg = new CompoundConfig(112 new MapConfig(ImmutableMap.of("server", ImmutableMap.of("allow-cors", "true"))));113 BaseServerOptions options = new BaseServerOptions(cfg);114 assertTrue("Allow CORS should be enabled", options.getAllowCORS());115 Server<?> server = new JettyServer(options, req -> new HttpResponse()).start();116 // TODO: Client setup117 URL url = server.getUrl();118 HttpClient client = HttpClient.Factory.createDefault().createClient(url);119 HttpRequest request = new HttpRequest(DELETE, "/session");120 String exampleUrl = "http://www.example.com";121 request.setHeader("Origin", exampleUrl);122 request.setHeader("Accept", "*/*");123 HttpResponse response = client.execute(request);124 // TODO: Assertion125 assertEquals("Access-Control-Allow-Credentials should be true", "true",126 response.getHeader("Access-Control-Allow-Credentials"));127 assertEquals("Access-Control-Allow-Origin should be equal to origin in request header",128 exampleUrl,129 response.getHeader("Access-Control-Allow-Origin"));130 }131}...

Full Screen

Full Screen

Source:NettyServerTest.java Github

copy

Full Screen

...86 request.setHeader("Accept", "*/*");87 HttpResponse response = client.execute(request);88 // TODO: Assertion89 assertEquals("Access-Control-Allow-Credentials should be null", null,90 response.getHeader("Access-Control-Allow-Credentials"));91 assertEquals("Access-Control-Allow-Origin should be null",92 null,93 response.getHeader("Access-Control-Allow-Origin"));94 }95 @Test96 @Ignore97 public void shouldAllowCORS() {98 // TODO: Server setup99 Config cfg = new CompoundConfig(100 new MapConfig(ImmutableMap.of("server", ImmutableMap.of("allow-cors", "true"))));101 BaseServerOptions options = new BaseServerOptions(cfg);102 assertTrue("Allow CORS should be enabled", options.getAllowCORS());103 // TODO: Server setup104 Server<?> server = new NettyServer(105 options,106 req -> new HttpResponse()107 ).start();108 // TODO: Client setup109 URL url = server.getUrl();110 HttpClient client = HttpClient.Factory.createDefault().createClient(url);111 HttpRequest request = new HttpRequest(DELETE, "/session");112 String exampleUrl = "http://www.example.com";113 request.setHeader("Origin", exampleUrl);114 request.setHeader("Accept", "*/*");115 HttpResponse response = client.execute(request);116 // TODO: Assertion117 assertEquals("Access-Control-Allow-Credentials should be true", "true",118 response.getHeader("Access-Control-Allow-Credentials"));119 assertEquals("Access-Control-Allow-Origin should be equal to origin in request header",120 exampleUrl,121 response.getHeader("Access-Control-Allow-Origin"));122 }123 private void outputHeaders(HttpResponse res) {124 res.getHeaderNames().forEach(name ->125 res.getHeaders(name).forEach(value -> System.out.printf("%s -> %s\n", name, value)));126 }127}...

Full Screen

Full Screen

Source:RemoteNewSessionQueuer.java Github

copy

Full Screen

...70 HttpRequest upstream =71 new HttpRequest(POST, "/se/grid/newsessionqueuer/session/retry/" + reqId.toString());72 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);73 upstream.setContent(request.getContent());74 upstream.setHeader(timestampHeader, request.getHeader(timestampHeader));75 upstream.setHeader(reqIdHeader, reqId.toString());76 HttpResponse response = client.execute(upstream);77 return Values.get(response, Boolean.class);78 }79 @Override80 public Optional<HttpRequest> remove() {81 HttpRequest upstream = new HttpRequest(GET, "/se/grid/newsessionqueuer/session");82 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);83 HttpResponse response = client.execute(upstream);84 if(response.getStatus()==HTTP_OK) {85 HttpRequest httpRequest = new HttpRequest(POST, "/session");86 httpRequest.setContent(response.getContent());87 httpRequest.setHeader(timestampHeader, response.getHeader(timestampHeader));88 httpRequest.setHeader(reqIdHeader, response.getHeader(reqIdHeader));89 return Optional.ofNullable(httpRequest);90 }91 return Optional.empty();92 }93 @Override94 public int clearQueue() {95 HttpRequest upstream = new HttpRequest(DELETE, "/se/grid/newsessionqueuer/queue");96 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);97 HttpResponse response = client.execute(upstream);98 return Values.get(response, Integer.class);99 }100 @Override101 public boolean isReady() {102 try {...

Full Screen

Full Screen

Source:ResourceHandlerTest.java Github

copy

Full Screen

...55 Files.createDirectories(dir);56 HttpHandler handler = new ResourceHandler(new PathResource(base));57 HttpResponse res = handler.execute(new HttpRequest(GET, "/cheese"));58 assertThat(res.getStatus()).isEqualTo(HTTP_MOVED_TEMP);59 assertThat(res.getHeader("Location")).endsWith("/cheese/");60 }61 @Test62 public void shouldLoadAnIndexPage() throws IOException {63 Path subdir = base.resolve("subdir");64 Files.createDirectories(subdir);65 Files.write(subdir.resolve("1.txt"), new byte[0]);66 Files.write(subdir.resolve("2.txt"), new byte[0]);67 HttpHandler handler = new ResourceHandler(new PathResource(base));68 HttpResponse res = handler.execute(new HttpRequest(GET, "/subdir/"));69 String text = Contents.string(res);70 assertThat(text).contains("1.txt");71 assertThat(text).contains("2.txt");72 }73 @Test74 public void canBeNestedWithinARoute() throws IOException {75 Path contents = base.resolve("cheese").resolve("cake.txt");76 Files.createDirectories(contents.getParent());77 Files.write(contents, "delicious".getBytes(UTF_8));78 HttpHandler handler = Route.prefix("/peas").to(Route.combine(new ResourceHandler(new PathResource(base))));79 // Check redirect works as expected80 HttpResponse res = handler.execute(new HttpRequest(GET, "/peas/cheese"));81 assertThat(res.getStatus()).isEqualTo(HTTP_MOVED_TEMP);82 assertThat(res.getHeader("Location")).isEqualTo("/peas/cheese/");83 // And now that content can be read84 res = handler.execute(new HttpRequest(GET, "/peas/cheese/cake.txt"));85 assertThat(res.getStatus()).isEqualTo(HTTP_OK);86 assertThat(Contents.string(res)).isEqualTo("delicious");87 }88}...

Full Screen

Full Screen

Source:BasicAuthenticationFilterTest.java Github

copy

Full Screen

...29 public void shouldAskAnUnauthenticatedRequestToAuthenticate() {30 HttpHandler handler = new BasicAuthenticationFilter("cheese", "cheddar").apply(req -> new HttpResponse());31 HttpResponse res = handler.execute(new HttpRequest(GET, "/"));32 assertThat(res.getStatus()).isEqualTo(HttpURLConnection.HTTP_UNAUTHORIZED);33 assertThat(res.getHeader("Www-Authenticate")).startsWith("Basic ");34 assertThat(res.getHeader("Www-Authenticate")).contains("Basic ");35 }36 @Test37 public void shouldAllowAuthenticatedTrafficThrough() {38 HttpHandler handler = new BasicAuthenticationFilter("cheese", "cheddar").apply(req -> new HttpResponse());39 HttpResponse res = handler.execute(40 new HttpRequest(GET, "/")41 .setHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString("cheese:cheddar".getBytes(UTF_8))));42 assertThat(res.isSuccessful()).isTrue();43 }44}...

Full Screen

Full Screen

getHeader

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.http.HttpRequest;2HttpRequest httpRequest = new HttpRequest("GET", "/status");3String header = httpRequest.getHeader("Content-Type");4System.out.println(header);5import org.openqa.selenium.remote.http.HttpRequest;6HttpRequest httpRequest = new HttpRequest("GET", "/status");7httpRequest.setHeader("Content-Type","application/json");8System.out.println(httpRequest.getHeader("Content-Type"));9import org.openqa.selenium.remote.http.HttpRequest;10HttpRequest httpRequest = new HttpRequest("GET", "/status");11httpRequest.setHeader("Content-Type","application/json");12System.out.println(httpRequest.getHeader("Content-Type"));13httpRequest.removeHeader("Content-Type");14System.out.println(httpRequest.getHeader("Content-Type"));15import org.openqa.selenium.remote.http.HttpRequest;16HttpRequest httpRequest = new HttpRequest("GET", "/status");17httpRequest.setHeader("Content-Type","application/json");18System.out.println(httpRequest.getHeaders());19import org.openqa.selenium.remote.http.HttpRequest;20HttpRequest httpRequest = new HttpRequest("GET", "/status");21httpRequest.setHeader("Content-Type","application/json");22System.out.println(httpRequest.getHeaderNames());23import org.openqa.selenium.remote.http.HttpRequest;24HttpRequest httpRequest = new HttpRequest("GET", "/status");25httpRequest.setHeader("Content-Type","application/json");26System.out.println(httpRequest.containsHeader("Content-Type"));27import org.openqa.selenium.remote.http.HttpRequest;28HttpRequest httpRequest = new HttpRequest("GET", "/status");29httpRequest.addHeader("Content-Type","application/json");30System.out.println(httpRequest.getHeader("Content-Type"));31import org.openqa.selenium.remote.http.HttpRequest;32HttpRequest httpRequest = new HttpRequest("GET", "/status");33httpRequest.addHeader("Content-Type","application/json");34System.out.println(httpRequest.getHeaders());35import org.openqa.selenium.remote.http.HttpRequest;36HttpRequest httpRequest = new HttpRequest("GET", "/status");

Full Screen

Full Screen

getHeader

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.http.HttpRequest;2String headerValue = request.getHeader("Content-Type");3System.out.println("Content-Type header value is: " + headerValue);4import org.openqa.selenium.remote.http.HttpRequest;5Map<String, String> headers = request.getHeaders();6System.out.println("Headers are: " + headers);7import org.openqa.selenium.remote.http.HttpRequest;8Set<String> headerNames = request.getHeaderNames();9System.out.println("Header names are: " + headerNames);10import org.openqa.selenium.remote.http.HttpRequest;11List<String> headerValues = request.getHeaderValues("Content-Type");12System.out.println("Content-Type header values are: " + headerValues);13import org.openqa.selenium.remote.http.HttpRequest;14List<String> headerValues = request.getHeaderValues("Content-Type");15System.out.println("Content-Type header values are: " + headerValues);16import org.openqa.selenium.remote.http.HttpRequest;17request.removeHeader("Content-Type");18import org.openqa.selenium.remote.http.HttpRequest;19request.removeHeaders("Content-Type");20import org.openqa.selenium.remote.http.HttpRequest;21request.removeHeader("Content-Type");22import org.openqa.selenium.remote.http.HttpRequest;23request.removeHeaders("Content-Type");24import org.openqa.selenium.remote.http.HttpRequest;25request.removeHeader("Content-Type");26import org.openqa.selenium.remote.http.HttpRequest;27request.removeHeaders("Content-Type");

Full Screen

Full Screen

getHeader

Using AI Code Generation

copy

Full Screen

1package com.seleniumcookbook.examples.chapter06;2import org.openqa.selenium.remote.http.HttpRequest;3import org.openqa.selenium.remote.http.HttpRequestHeader;4public class GetHeaders {5 public static void main(String[] args) {6 request.addHeader("Accept", "text/html");7 request.addHeader("Accept", "application/xhtml+xml");8 request.addHeader("Accept", "application/xml;q=0.9,*/*;q=0.8");9 System.out.println("Headers: " + request.getHeaders().toString());10 }11}12Headers: [Accept: text/html, Accept: application/xhtml+xml, Accept: application/xml;q=0.9,*/*;q=0.8]13package com.seleniumcookbook.examples.chapter06;14import org.openqa.selenium.remote.http.HttpRequest;15import org.openqa.selenium.remote.http.HttpRequestHeader;16public class RemoveHeader {17 public static void main(String[] args) {18 request.addHeader("Accept", "text/html");19 request.addHeader("Accept", "application/xhtml+xml");20 request.addHeader("Accept", "application/xml;q=0.9,*/*;q=0.8");21 request.removeHeader("Accept");22 System.out.println("Headers: " + request.getHeaders().toString());23 }24}25package com.seleniumcookbook.examples.chapter06;26import org.openqa.selenium.remote.http.HttpRequest;27import org.openqa.selenium.remote.http.HttpRequestHeader;28public class SetHeader {29 public static void main(String[] args) {30 request.addHeader("Accept", "text/html");31 request.addHeader("Accept", "application

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