Best Selenium code snippet using org.openqa.selenium.remote.http.HttpResponse.setHeader
Source: ProtocolConverterTest.java
...55 OSS) {56 @Override57 protected HttpResponse makeRequest(HttpRequest request) {58 HttpResponse response = new HttpResponse();59 response.setHeader("Content-Type", MediaType.JSON_UTF_8.toString());60 response.setHeader("Cache-Control", "none");61 Map<String, Object> obj = new HashMap<>();62 obj.put("sessionId", sessionId.toString());63 obj.put("status", 0);64 obj.put("value", null);65 String payload = json.toJson(obj);66 response.setContent(utf8String(payload));67 return response;68 }69 };70 Command command = new Command(71 sessionId,72 DriverCommand.GET,73 ImmutableMap.of("url", "http://example.com/cheese"));74 HttpRequest w3cRequest = new W3CHttpCommandCodec().encode(command);75 HttpResponse resp = new HttpResponse();76 handler.execute(w3cRequest, resp);77 assertEquals(MediaType.JSON_UTF_8, MediaType.parse(resp.getHeader("Content-type")));78 assertEquals(HttpURLConnection.HTTP_OK, resp.getStatus());79 Map<String, Object> parsed = json.toType(string(resp), MAP_TYPE);80 assertNull(parsed.toString(), parsed.get("sessionId"));81 assertTrue(parsed.toString(), parsed.containsKey("value"));82 assertNull(parsed.toString(), parsed.get("value"));83 }84 @Test85 public void shouldAliasAComplexCommand() throws IOException {86 SessionId sessionId = new SessionId("1234567");87 // Downstream is JSON, upstream is W3C. This way we can force "isDisplayed" to become JS88 // execution.89 CommandHandler handler = new ProtocolConverter(90 HttpClient.Factory.createDefault().createClient(new URL("http://example.com/wd/hub")),91 OSS,92 W3C) {93 @Override94 protected HttpResponse makeRequest(HttpRequest request) {95 assertEquals(String.format("/session/%s/execute/sync", sessionId), request.getUri());96 Map<String, Object> params = json.toType(string(request), MAP_TYPE);97 assertEquals(98 ImmutableList.of(99 ImmutableMap.of(W3C.getEncodedElementKey(), "4567890")),100 params.get("args"));101 HttpResponse response = new HttpResponse();102 response.setHeader("Content-Type", MediaType.JSON_UTF_8.toString());103 response.setHeader("Cache-Control", "none");104 Map<String, Object> obj = ImmutableMap.of(105 "sessionId", sessionId.toString(),106 "status", 0,107 "value", true);108 String payload = json.toJson(obj);109 response.setContent(utf8String(payload));110 return response;111 }112 };113 Command command = new Command(114 sessionId,115 DriverCommand.IS_ELEMENT_DISPLAYED,116 ImmutableMap.of("id", "4567890"));117 HttpRequest w3cRequest = new JsonHttpCommandCodec().encode(command);118 HttpResponse resp = new HttpResponse();119 handler.execute(w3cRequest, resp);120 assertEquals(MediaType.JSON_UTF_8, MediaType.parse(resp.getHeader("Content-type")));121 assertEquals(HttpURLConnection.HTTP_OK, resp.getStatus());122 Map<String, Object> parsed = json.toType(string(resp), MAP_TYPE);123 assertNull(parsed.get("sessionId"));124 assertTrue(parsed.containsKey("value"));125 assertEquals(true, parsed.get("value"));126 }127 @Test128 public void shouldConvertAnException() throws IOException {129 // Json upstream, w3c downstream130 SessionId sessionId = new SessionId("1234567");131 CommandHandler handler = new ProtocolConverter(132 HttpClient.Factory.createDefault().createClient(new URL("http://example.com/wd/hub")),133 W3C,134 OSS) {135 @Override136 protected HttpResponse makeRequest(HttpRequest request) {137 HttpResponse response = new HttpResponse();138 response.setHeader("Content-Type", MediaType.JSON_UTF_8.toString());139 response.setHeader("Cache-Control", "none");140 String payload = new Json().toJson(141 ImmutableMap.of(142 "sessionId", sessionId.toString(),143 "status", UNHANDLED_ERROR,144 "value", new WebDriverException("I love cheese and peas")));145 response.setContent(utf8String(payload));146 response.setStatus(HTTP_INTERNAL_ERROR);147 return response;148 }149 };150 Command command = new Command(151 sessionId,152 DriverCommand.GET,153 ImmutableMap.of("url", "http://example.com/cheese"));...
Source: JettyServerTest.java
...94 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}...
Source: NettyServerTest.java
...77 URL url = server.getUrl();78 HttpClient client = HttpClient.Factory.createDefault().createClient(url);79 HttpRequest request = new HttpRequest(DELETE, "/session");80 String exampleUrl = "http://www.example.com";81 request.setHeader("Origin", exampleUrl);82 request.setHeader("Accept", "*/*");83 HttpResponse response = client.execute(request);84 assertNull("Access-Control-Allow-Origin should be null",85 response.getHeader("Access-Control-Allow-Origin"));86 }87 @Test88 public void shouldAllowCORS() {89 Config cfg = new CompoundConfig(90 new MapConfig(ImmutableMap.of("server", ImmutableMap.of("allow-cors", "true"))));91 BaseServerOptions options = new BaseServerOptions(cfg);92 assertTrue("Allow CORS should be enabled", options.getAllowCORS());93 // TODO: Server setup94 Server<?> server = new NettyServer(95 options,96 req -> new HttpResponse()97 ).start();98 URL url = server.getUrl();99 HttpClient client = HttpClient.Factory.createDefault().createClient(url);100 HttpRequest request = new HttpRequest(DELETE, "/session");101 request.setHeader("Origin", "http://www.example.com");102 request.setHeader("Accept", "*/*");103 HttpResponse response = client.execute(request);104 assertEquals(105 "Access-Control-Allow-Origin should be equal to origin in request header",106 "*",107 response.getHeader("Access-Control-Allow-Origin"));108 }109 private void outputHeaders(HttpResponse res) {110 res.getHeaderNames()111 .forEach(name ->112 res.getHeaders(name)113 .forEach(value -> System.out.printf("%s -> %s\n", name, value)));114 }115}...
Source: RemoteNewSessionQueuer.java
...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 {...
Source: SleepingHandler.java
...28 String duration = req.getQueryParameter("time");29 long timeout = Long.parseLong(duration) * 1000;30 reallySleep(timeout);31 return new HttpResponse()32 .setHeader("Content-Type", "text/html")33 //Dont Cache Anything at the browser34 .setHeader("Cache-Control","no-cache")35 .setHeader("Pragma","no-cache")36 .setHeader("Expires", "0")37 .setContent(utf8String(String.format(RESPONSE_STRING_FORMAT, duration)));38 }39 private void reallySleep(long timeout) {40 long start = System.currentTimeMillis();41 try {42 Thread.sleep(timeout);43 while ( (System.currentTimeMillis() - start) < timeout) {44 Thread.sleep( 20);45 }46 } catch (InterruptedException ignore) {47 }48 }49}...
Source: ErrorHandler.java
...30 }31 @Override32 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {33 return new HttpResponse()34 .setHeader("Cache-Control", "none")35 .setHeader("Content-Type", JSON_UTF_8.toString())36 .setStatus(errors.getHttpStatusCode(throwable))37 .setContent(asJson(errors.encode(throwable)));38 }39}...
setHeader
Using AI Code Generation
1import org.openqa.selenium.remote.http.HttpResponse;2import org.openqa.selenium.remote.http.HttpHeaders;3import org.openqa.selenium.remote.http.HttpHeader;4import org.openqa.selenium.remote.http.HttpMethod;5HttpResponse response = new HttpResponse();6response.setHeader(HttpHeader.CONTENT_TYPE, "text/plain");7response.setHeader(HttpHeader.CONTENT_LENGTH, "13");8response.setContent("Hello, world!");9response.setStatus(200);10response.setStatusText("OK");11System.out.println(response.toString());12I have another question, I am trying to get the response headers from the request. I found the method getHeaders() in the class HttpResponse, but it returns a Map<String, String> and I don’t know how to get the headers. Can you help me?13import org.openqa.selenium.remote.http.HttpResponse;14import org.openqa.selenium.remote.http.HttpHeaders;15import org.openqa.selenium.remote.http.HttpHeader;16import org.openqa.selenium.remote.http.HttpMethod;17HttpResponse response = new HttpResponse();18response.setHeader(HttpHeader.CONTENT_TYPE, "text/plain");19response.setHeader(HttpHeader.CONTENT_LENGTH, "13");20response.setContent("Hello, world!");21response.setStatus(200);22response.setStatusText("OK");23System.out.println(response.getHeaders());24I have another question, I am trying to get the response headers from the request. I found the method getHeaders() in the class HttpResponse, but it returns a Map<String, String>
setHeader
Using AI Code Generation
1import org.openqa.selenium.remote.http.HttpResponse2import org.openqa.selenium.remote.http.Headers3import org.openqa.selenium.remote.http.HttpMethod4import org.openqa.selenium.remote.http.HttpRequest5import org.openqa.selenium.remote.http.HttpClient6import org.openqa.selenium.remote.http.HttpResponse7HttpResponse response = new HttpResponse()8response.setHeader("Content-Type", "text/html")9HttpClient client = new HttpClient()10response = client.execute(request)11println response.getHeader("Content-Type")12println response.getContent()13println response.getStatus()14println response.getStatusMessage()15Headers headers = response.getHeaders()16List cookies = response.getCookies()17String contentType = response.getContentType()18int contentLength = response.getContentLength()19String content = response.getContent()20byte[] contentAsByteArray = response.getContentAsByteArray()21String contentAsString = response.getContentAsString()22Map contentAsJson = response.getContentAsJson()23Document contentAsXml = response.getContentAsXml()24File contentAsFile = response.getContentAsFile()25InputStream contentAsInputStream = response.getContentAsInputStream()26Reader contentAsReader = response.getContentAsReader()27ReadableByteChannel contentAsReadableByteChannel = response.getContentAsReadableByteChannel()28ByteBuffer contentAsByteBuffer = response.getContentAsByteBuffer()29ByteBuffer contentAsByteBufferWithCapacity = response.getContentAsByteBuffer(1024)
setHeader
Using AI Code Generation
1import org.openqa.selenium.remote.http.HttpResponse2def response = new HttpResponse()3response.setHeader("Content-Type", "text/html")4import org.openqa.selenium.remote.http.HttpResponse5def response = new HttpResponse()6response.setHeader("Content-Type", "text/html")7String contentType = response.getHeader("Content-Type")8import org.openqa.selenium.remote.http.HttpResponse9def response = new HttpResponse()10response.addHeader("Content-Type", "text/html")11import org.openqa.selenium.remote.http.HttpResponse12def response = new HttpResponse()13response.setHeader("Content-Type", "text/html")14response.removeHeader("Content-Type")15import org.openqa.selenium.remote.http.HttpResponse16def response = new HttpResponse()17response.setHeader("Content-Type", "text/html")18response.setHeader("Content-Encoding", "gzip")19List<String> headers = response.getHeaders("Content-Type")20import org.openqa.selenium.remote.http.HttpResponse21def response = new HttpResponse()22response.setHeader("Content-Type", "text/html")23response.setHeader("Content-Encoding", "gzip")24List<String> headerNames = response.getHeaderNames()25import org.openqa.selenium.remote.http.HttpResponse26def response = new HttpResponse()27response.setHeader("Content-Type", "text/html")28response.setHeader("Content-Encoding", "gzip")29List<String> headerValues = response.getHeaderValues("Content-Type")30import org.openqa.selenium.remote.http.HttpResponse31def response = new HttpResponse()32response.setHeader("Content-Type", "text/html")33response.setHeader("Content-Encoding", "gzip")34response.setHeaderValues("Content-Type", ["text/html", "text/plain"])35import org.openqa.selenium.remote.http.HttpResponse36def response = new HttpResponse()37response.setHeader("Content-Type", "text/html")38response.setHeader("Content-Encoding", "gzip")39List<String> headerValues = response.getHeaderValues("Content-Type")
setHeader
Using AI Code Generation
1import org.openqa.selenium.remote.http.HttpResponse;2HttpResponse response = new HttpResponse();3response.setHeader("content-type", "text/html");4import org.openqa.selenium.remote.http.HttpResponse;5HttpResponse response = new HttpResponse();6response.setHeader("content-type", "text/html");7import org.openqa.selenium.remote.http.HttpResponse;8HttpResponse response = new HttpResponse();9response.setHeader("content-type", "text/html");10import org.openqa.selenium.remote.http.HttpResponse;11HttpResponse response = new HttpResponse();12response.setHeader("content-type", "text/html");13import org.openqa.selenium.remote.http.HttpResponse;14HttpResponse response = new HttpResponse();15response.setHeader("content-type", "text/html");16import org.openqa.selenium.remote.http.HttpResponse;17HttpResponse response = new HttpResponse();18response.setHeader("content-type", "text/html");19import org.openqa.selenium.remote.http.HttpResponse;20HttpResponse response = new HttpResponse();21response.setHeader("content-type", "text/html");22import org.openqa.selenium.remote.http.HttpResponse;23HttpResponse response = new HttpResponse();24response.setHeader("content-type", "text/html");25import org.openqa.selenium.remote.http.HttpResponse;26HttpResponse response = new HttpResponse();27response.setHeader("content-type", "text/html");28import org.openqa.selenium.remote.http.HttpResponse;
setHeader
Using AI Code Generation
1HttpResponse response = new HttpResponse();2response.setHeader("Content-Type", "application/json");3System.out.println(response.getHeader("Content-Type"));4System.out.println(response.getHeaders());5response.removeHeader("Content-Type");6System.out.println(response.getHeaders());7System.out.println(response.hasHeader("Content-Type"));8System.out.println(response.hasHeader("Content-Length"));9{Content-Type=[application/json]}10{}
How to override basic authentication in selenium2 with Java using chrome driver?
How to reuse JUnit Jupiter @MethodSource for multiple parameterized tests
Selenium findElements() returns the same instance of the first element multiple times
Java: call a method with name stored in variable
Cucumber Selenium - fill in web form
Detect from selenium if angular is doing ... stuff
How can I click on a button using Selenium WebDriver with Java?
Bad parameters: BadParametersError: Parameters were incorrect. We wanted required capabilities on Selenium grid while running Appium
Cannot resolve com.sun:tools:0 in Maven Project?
Selenium abotring with "UnreachableBrowserException/Address already in use" occurring on one computer
I've struggled with the same problem over an hour and finally @kenorb's solution rescued me. To be short you need to add a browser extension that does the authentication for you (since Selenium itself can't do that!).
Here is how it works for Chrome and Python:
background.js
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: "YOU_PROXY_ADDRESS",
port: parseInt(YOUR_PROXY_PORT)
},
bypassList: ["foobar.com"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "YOUR_PROXY_USERNAME",
password: "YOUR_PROXY_PASSWORD"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
Don't forget to replace YOUR_PROXY_* to your settings.
manifest.json
{
"version": "1.0.0",
"manifest_version": 2,
"name": "Chrome Proxy",
"permissions": [
"proxy",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
},
"minimum_chrome_version":"22.0.0"
}
Add the created proxy.zip as an extension
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_extension("proxy.zip")
driver = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=chrome_options)
driver.get("http://google.com")
driver.close()
That's it. For me that worked like a charm. If you need to create proxy.zip dynamically or need PHP example then go to the original post
Check out the latest blogs from LambdaTest on this topic:
The goals we are trying to achieve here by using Machine Learning for automation in testing are to dynamically write new test cases based on user interactions by data-mining their logs and their behavior on the application / service for which tests are to be written, live validation so that in case if an object is modified or removed or some other change like “modification in spelling” such as done by most of the IDE’s in the form of Intelli-sense like Visual Studio or Eclipse.
E2E Testing also called End to End testing, is a very common testing methodology where the objective is to test how an application works by checking the flow from start to end. Not only the application flow under dev environment is tested, but the tester also has to check how it behaves once integrated with the external interface. Usually, this testing phase is executed after functional testing and system testing is completed. The technical definition of end to end testing is – a type of testing to ensure that behavioural flow of an application works as expected by performing a complete, thorough testing, from the beginning to end of the product-user interaction in order to realize any dependency or flaw in the workflow of the application.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium JavaScript Tutorial.
As you start on with automation you may come across various approaches, techniques, framework and tools you may incorporate in your automation code. Sometimes such versatility leads to greater complexity in code than providing better flexibility or better means of resolving issues. While writing an automation code it’s important that we are able to clearly portray our objective of automation testing and how are we achieving it. Having said so it’s important to write ‘clean code’ to provide better maintainability and readability. Writing clean code is also not an easy cup of tea, you need to keep in mind a lot of best practices. The below topic highlights 8 silver lines one should acquire to write better automation code.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Cross Browser Testing 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.
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.
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.
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.
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.
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.
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.
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.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!