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

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

Source:OkHttpClient.java Github

copy

Full Screen

...49 HttpResponse toReturn = new HttpResponse();50 toReturn.setContent(response.body() == null ? empty() : bytes(response.body().bytes()));51 toReturn.setStatus(response.code());52 response.headers().names().forEach(53 name -> response.headers(name).forEach(value -> toReturn.addHeader(name, value)));54 return toReturn;55 }56 @Override57 public WebSocket openSocket(HttpRequest request, WebSocket.Listener listener) {58 Objects.requireNonNull(request, "Request to send must be set.");59 Objects.requireNonNull(listener, "WebSocket listener must be set.");60 Request okHttpRequest = buildOkHttpRequest(request);61 return new OkHttpWebSocket(client, okHttpRequest, listener);62 }63 private Request buildOkHttpRequest(HttpRequest request) {64 Request.Builder builder = new Request.Builder();65 HttpUrl.Builder url;66 String rawUrl;67 if (request.getUri().startsWith("ws://")) {68 rawUrl = "http://" + request.getUri().substring("ws://".length());69 } else if (request.getUri().startsWith("wss://")) {70 rawUrl = "https://" + request.getUri().substring("wss://".length());71 } else if (request.getUri().startsWith("http://") || request.getUri().startsWith("https://")) {72 rawUrl = request.getUri();73 } else {74 rawUrl = baseUrl.toExternalForm().replaceAll("/$", "") + request.getUri();75 }76 HttpUrl parsed = HttpUrl.parse(rawUrl);77 if (parsed == null) {78 throw new UncheckedIOException(79 new IOException("Unable to parse URL: " + baseUrl.toString() + request.getUri()));80 }81 url = parsed.newBuilder();82 for (String name : request.getQueryParameterNames()) {83 for (String value : request.getQueryParameters(name)) {84 url.addQueryParameter(name, value);85 }86 }87 builder.url(url.build());88 for (String name : request.getHeaderNames()) {89 for (String value : request.getHeaders(name)) {90 builder.addHeader(name, value);91 }92 }93 if (request.getHeader("User-Agent") == null) {94 builder.addHeader("User-Agent", USER_AGENT);95 }96 switch (request.getMethod()) {97 case GET:98 builder.get();99 break;100 case POST:101 String rawType = Optional.ofNullable(request.getHeader("Content-Type"))102 .orElse("application/json; charset=utf-8");103 MediaType type = MediaType.parse(rawType);104 RequestBody body = RequestBody.create(type, bytes(request.getContent()));105 builder.post(body);106 break;107 case DELETE:108 builder.delete();...

Full Screen

Full Screen

Source:ResourceHandler.java Github

copy

Full Screen

...74 if (!req.getUri().endsWith("/")) {75 String dest = UrlPath.relativeToContext(req, req.getUri() + "/");76 return new HttpResponse()77 .setStatus(HTTP_MOVED_TEMP)78 .addHeader("Location", dest);79 }80 String links = resource.list().stream()81 .map(res -> String.format("<li><a href=\"%s\">%s</a>", res.name(), res.name()))82 .sorted()83 .collect(Collectors.joining("\n", "<ul>\n", "</ul>\n"));84 String html = String.format(85 "<html><title>Listing of %s</title><body><h1>%s</h1>%s",86 resource.name(),87 resource.name(),88 links);89 return new HttpResponse()90 .addHeader("Content-Type", HTML_UTF_8.toString())91 .setContent(utf8String(html));92 }93 private HttpResponse readFile(HttpRequest req, Resource resource) {94 Optional<byte[]> bytes = resource.read();95 if (bytes.isPresent()) {96 return new HttpResponse()97 .addHeader("Content-Type", mediaType(req.getUri()))98 .setContent(bytes(bytes.get()));99 }100 return get404(req);101 }102 private HttpResponse get404(HttpRequest req) {103 return new HttpResponse()104 .setStatus(HTTP_NOT_FOUND)105 .setContent(utf8String("Unable to read " + req.getUri()));106 }107 private String mediaType(String uri) {108 int index = uri.lastIndexOf(".");109 String extension = (index == -1 || uri.length() == index) ? "" : uri.substring(index + 1);110 MediaType type;111 switch (extension.toLowerCase()) {...

Full Screen

Full Screen

Source:ReverseProxyHandlerTest.java Github

copy

Full Screen

...52 @Test53 public void shouldForwardRequestsToEndPoint() throws IOException {54 CommandHandler handler = new ReverseProxyHandler(factory.createClient(server.url));55 HttpRequest req = new HttpRequest(HttpMethod.GET, "/ok");56 req.addHeader("X-Cheese", "Cake");57 HttpResponse resp = new HttpResponse();58 handler.execute(req, resp);59 // HTTP headers are case insensitive. This is how the HttpUrlConnection likes to encode things60 assertEquals("Cake", server.lastRequest.getHeader("x-cheese"));61 }62 private static class Server {63 private final URL url;64 private final HttpServer server;65 private HttpRequest lastRequest;66 public Server() throws IOException {67 int port = PortProber.findFreePort();68 String address = new NetworkUtils().getPrivateLocalAddress();69 url = new URL("http", address, port, "/ok");70 server = HttpServer.create(new InetSocketAddress(address, port), 0);71 server.createContext("/ok", ex -> {72 lastRequest = new HttpRequest(73 HttpMethod.valueOf(ex.getRequestMethod()),74 ex.getRequestURI().getPath());75 Headers headers = ex.getRequestHeaders();76 for (Map.Entry<String, List<String>> entry : headers.entrySet()) {77 for (String value : entry.getValue()) {78 lastRequest.addHeader(entry.getKey().toLowerCase(), value);79 }80 }81 try (InputStream in = ex.getRequestBody()) {82 lastRequest.setContent(bytes(ByteStreams.toByteArray(in)));83 }84 byte[] payload = "I like cheese".getBytes(UTF_8);85 ex.sendResponseHeaders(HTTP_OK, payload.length);86 try (OutputStream out = ex.getResponseBody()) {87 out.write(payload);88 }89 });90 server.start();91 }92 public void stop() {...

Full Screen

Full Screen

Source:EnsureSpecCompliantHeadersTest.java Github

copy

Full Screen

...49 HttpResponse res = new EnsureSpecCompliantHeaders(ImmutableList.of(), ImmutableSet.of())50 .apply(alwaysOk)51 .execute(52 new HttpRequest(POST, "/session")53 .addHeader("Content-Type", JSON_UTF_8)54 .addHeader("Origin", "example.com"));55 assertThat(res.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR);56 }57 @Test58 public void requestsWithAnAllowedOriginHeaderShouldBeAllowed() {59 HttpResponse res = new EnsureSpecCompliantHeaders(ImmutableList.of("example.com"), ImmutableSet.of())60 .apply(alwaysOk)61 .execute(62 new HttpRequest(POST, "/session")63 .addHeader("Content-Type", JSON_UTF_8)64 .addHeader("Origin", "example.com"));65 assertThat(res.getStatus()).isEqualTo(HTTP_OK);66 assertThat(Contents.string(res)).isEqualTo("Cheese");67 }68 @Test69 public void shouldAllowRequestsWithNoOriginHeader() {70 HttpResponse res = new EnsureSpecCompliantHeaders(ImmutableList.of(), ImmutableSet.of())71 .apply(alwaysOk)72 .execute(73 new HttpRequest(POST, "/session")74 .addHeader("Content-Type", JSON_UTF_8));75 assertThat(res.getStatus()).isEqualTo(HTTP_OK);76 assertThat(Contents.string(res)).isEqualTo("Cheese");77 }78}...

Full Screen

Full Screen

Source:NettyMessages.java Github

copy

Full Screen

...47 }48 }49 for (String name : request.getHeaderNames()) {50 for (String value : request.getHeaders(name)) {51 builder.addHeader(name, value);52 }53 }54 if (request.getMethod().equals(HttpMethod.POST)) {55 builder.setBody(request.getContent().get());56 }57 return builder.build();58 }59 public static HttpResponse toSeleniumResponse(Response response) {60 HttpResponse toReturn = new HttpResponse();61 toReturn.setStatus(response.getStatusCode());62 toReturn.setContent(! response.hasResponseBody()63 ? empty()64 : Contents.memoize(response::getResponseBodyAsStream));65 response.getHeaders().names().forEach(66 name -> response.getHeaders(name).forEach(value -> toReturn.addHeader(name, value)));67 return toReturn;68 }69}...

Full Screen

Full Screen

Source:PullImage.java Github

copy

Full Screen

...38 public void apply(Reference ref) {39 Require.nonNull("Reference to pull", ref);40 LOG.info("Pulling " + ref);41 HttpRequest req = new HttpRequest(POST, "/v1.40/images/create")42 .addHeader("Content-Type", JSON_UTF_8)43 .addHeader("Content-Length", "0")44 .addQueryParameter("fromImage", String.format("%s/%s", ref.getRepository(), ref.getName()));45 if (ref.getDigest() != null) {46 req.addQueryParameter("tag", ref.getDigest());47 } else if (ref.getTag() != null) {48 req.addQueryParameter("tag", ref.getTag());49 }50 HttpResponse res = client.execute(req);51 LOG.info("Have response from server");52 if (!res.isSuccessful()) {53 String message = "Unable to pull image: " + ref.getFamiliarName();54 try {55 Map<String, Object> value = JSON.toType(Contents.string(res), MAP_TYPE);56 message = (String) value.get("message");57 } catch (Exception e) {...

Full Screen

Full Screen

Source:GetContainerLogs.java Github

copy

Full Screen

...39 String requestUrl =40 String.format("/v%s/containers/%s/logs?stdout=true&stderr=true", DOCKER_API_VERSION, id);41 HttpResponse res = client.execute(42 new HttpRequest(GET, requestUrl)43 .addHeader("Content-Length", "0")44 .addHeader("Content-Type", "text/plain"));45 if (res.getStatus() != HTTP_OK) {46 LOG.warning("Unable to inspect container " + id);47 }48 List<String> logLines = Arrays.asList(Contents.string(res).split("\n"));49 return new ContainerLogs(id, logLines);50 }51}...

Full Screen

Full Screen

addHeader

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.http.HttpRequest;2import org.openqa.selenium.remote.http.HttpResponse;3import java.net.URI;4import java.net.URISyntaxException;5public class AddHeaderExample {6 public static void main(String[] args) throws URISyntaxException {7 request.addHeader("Content-Type", "application/json");8 HttpResponse response = new HttpResponse();9 response.addHeader("Content-Type", "application/json");10 System.out.println(request);11 System.out.println(response);12 }13}14import org.openqa.selenium.remote.http.HttpRequest;15import org.openqa.selenium.remote.http.HttpResponse;16import java.net.URI;17import java.net.URISyntaxException;18public class AddHeaderExample {19 public static void main(String[] args) throws URISyntaxException {20 request.addHeader("Content-Type", "application/json");21 HttpResponse response = new HttpResponse();22 response.addHeader("Content-Type", "application/json");23 System.out.println(request);24 System.out.println(response);25 }26}27import org.openqa.selenium.remote.http.HttpRequest;28import org.openqa.selenium.remote.http.HttpResponse;29import java.net.URI;30import java.net.URISyntaxException;31public class AddHeaderExample {32 public static void main(String[] args) throws URISyntaxException {33 request.addHeader("Content-Type", "application/json");34 HttpResponse response = new HttpResponse();

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