Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Selenium WebDriver to modify HTTP request headers in JAVA

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how to use Selenium WebDriver to modify the HTTP request header in JAVA. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

What is a HTTP header

HTTP header is an important part of HTTP protocol. They define HTTP messages (requests or responses) and allow clients and servers to exchange optional metadata with the message. They consist of a case-insensitive header field name followed by a colon followed by a header field value. The header field can be extended to multiple lines by having at least one space or horizontal tab before each additional line.

Headings can be grouped according to their context:

Request header: the HTTP request header is used to provide additional information about the resource being acquired and the client that made the request.

Response header: the HTTP response header provides information about the response. The Location header specifies the location of the resource, and the server header provides information about the server that provides the resource.

Presentation header: HTTP indicates that the header is an important part of any HTTP response. They provide information about protocol elements, such as MIME type, character encoding, and so on. This makes them an important part of processing resources through Internet.

Payload header: the HTTP payload header contains data about the HTTP message payload, such as its length and coding, but is independent of the presentation.

Take a closer look at HTTP request headers

A HTTP request header is a communication mechanism that enables a browser or client to request a specific web page or data from a (Web) server. When used in Web communication or Internet browsing, the HTTP request header enables browsers and clients to communicate with the appropriate Web server by sending requests.

The HTTP request header describes the request sent by the Web browser to load the page. It is also called client-to-server protocol. The header includes details of the client request, such as the type of browser and operating system the user uses, as well as other parameters required to display the request correctly on the screen.

The following is the main information contained in the HTTP request header:

IP address (source) and port number.

The URL of the requested web page.

Web server or target website (host).

The type of data that the browser will accept (text, html, xml, etc.).

The type of browser that sends compatible data (Mozilla, Chrome, IE).

In response, the HTTP response header containing the request data is sent back.

Need to change the HTTP request header

Can you guess why we even need to change the request header after it has been set in the script?

Here are some scenarios where you may need to change the HTTP request header:

Test control and / or test different variants by establishing appropriate HTTP headers.

Situations that require thorough testing of different aspects of the Web application and even server logic.

Because the HTTP request header is used to enable certain parts of the Web application logic, which is usually disabled in normal mode, depending on the test scenario, the HTTP request header may need to be modified from time to time.

Testing the guest mode on the Web application under test is an ideal situation where you may need to modify the HTTP request header.

But the ability to modify HTTP request headers once supported by Selenium RC is no longer handled by Selenium Webdriver.

This is why we change the header request when writing test automation projects using the Selenium framework and Java.

How to modify a header request in a Selenium Java project

In this part of the Selenium Java tutorial, we will learn about several ways to modify header requests in Java. In general, there are several possibilities, and then you can modify the header request in the Java-Selenium project.

Use drivers / libraries like REST Assured instead of Selenium.

Use reverse proxies, such as browser mob-proxy or some other proxy mechanism.

Use the Firefox browser extension, which will help modify the header of the request.

Let's explore each possibility one by one:

Use the REST Assured library to modify the HTTP request header

Along with Selenium, we can use REST Assured, which is an excellent tool for using REST services in a simple way.

The prerequisites for configuring REST Assured for your project in any IDE (such as Eclipse) are simple. After setting up Java, Eclipse and TestNG, you need to download the required REST Assured jar files.

After downloading the jar file, you must create a project in Eclipse and add the downloaded jar file to the Properties section as an external jar. This is once again similar to the way we add the Selenium jar file to the project. Once you have successfully set up the Java project using the REST Assured library, you are ready to start.

We intend to create a mechanism so that the request header can be customized. In order to achieve this with the above possibilities, we first need to understand the general method of creating request headers.

Let's consider the following scenarios:

We have a Java class called RequestHeaderChangeDemo, where we maintain the basic configuration

We have a test step file called TestSteps, where we will call the methods in the RequestHeaderChangeDemo Java class, through which we will execute our tests.

Observe the following Java class named RequestHeaderChangeDemo.

BASE_URL is an Amazon website that applies the following four methods:

Authenticated user

Get the product

Add a product

Remove the product

Public class RequestHeaderChangeDemo {private static final String BASE_URL = "https://amazon.com"; public static IRestResponse authenticateUser (AuthorizationRequest authRequest) {RestAssured.baseURI = BASE_URL; RequestSpecification request = RestAssured.given (); request.header (" Content-Type "," application/json "); Response response = request.body (authRequest) .post (Route.generateToken ()); return new RestResponse (Token.class, response) } public static IRestResponse getProducts () {RestAssured.baseURI = BASE_URL; RequestSpecification request = RestAssured.given (); request.header ("Content-Type", "application/json"); Response response = request.get (Route.products ()); return new RestResponse (Products.class, response);} public static IRestResponse addProduct (AddProductsRequest addProductsRequest, String token) {RestAssured.baseURI = BASE_URL; RequestSpecification request = RestAssured.given () Request.header ("Authorization", "Bearer" + token) .header ("Content-Type", "application/json"); Response response = request.body (addProductsRequest) .post (Route.products ()); return new RestResponse (UserAccount.class, response);} public static Response removeProduct (RemoveProductRequest removeProductRequest, String token) {RestAssured.baseURI = BASE_URL; RequestSpecification request = RestAssured.given () Request.header ("Authorization", "Bearer" + token) .header ("Content-Type", "application/json"); return request.body (removeProductRequest) .delete (Route.product ());,}}

In the Java class file above, we repeatedly sent BASE_URL and headers in each successive method. The example is as follows:

RestAssured.baseURI = BASE_URL;RequestSpecification request = RestAssured.given (); request.header ("Content-Type", "application/json"); Response response = request.body (authRequest) .post (Route.generateToken ())

The request.header method requests a header in JSON format. There is a lot of code duplication, which reduces the maintainability of the code.

This can be avoided if we initialize the RequestSpecification object in the constructor and make these methods non-static (that is, create instance methods).

Because the instance method in Java belongs to the Object of the class rather than the class itself, it can be called even after you create the Object of the class. At the same time, we will also override the instance method.

Converting a method to an instance method has the following advantages:

Authentication occurs only once in a RequestSpecification object. You no longer need to create the same request for other requests.

Modify the request headers in the project flexibly.

So let's take a look at the appearance of the Java class RequestHeaderChangeDemo and the test step file TestSteps when we use the instance method.

The Java class of the RequestHeaderChangeDemo class with instance methods:

Public class RequestHeaderChangeDemo {private final RequestSpecification request; public RequestHeaderChangeDemo (String baseUrl) {RestAssured.baseURI = baseUrl; request = RestAssured.given (); request.header ("Content-Type", "application/json");} public void authenticateUser (AuthorizationRequest authRequest) {Response response = request.body (authRequest) .post (Route.generateToken ()) If (response.statusCode ()! = HttpStatus.SC_OK) throw new RuntimeException ("Authentication Failed. Content of failed Response: "+ response.toString () +", Status Code: "+ response.statusCode (); Token tokenResponse = response.body (). JsonPath (). GetObject (" $", Token.class); request.header (" Authorization "," Bearer "+ tokenResponse.token);} public IRestResponse getProducts () {Response response = request.get (Route.products ()) Return new RestResponse (Products.class, response);} public IRestResponse addProduct (AddProductsRequest addProductsRequest) {Response response = request.body (addProductsRequest) .post (Route.products ()); return new RestResponse (UserAccount.class, response);} public Response removeProducts (RemoveProductRequest removeProductRequest) {return request.body (removeProductRequest) .delete (Route.product ());}}

We created a constructor to initialize the RequestSpecification object that contains the BaseURL and request headers. Code exercise

Earlier, we had to pass tokens in each request header. Now, once we receive a token response in the method authenticateUser (), we put it in the same instance of the request. This allows the execution of the test steps to move forward without having to add tokens for each request as before. This makes the header available for subsequent calls to the server.

The RequestHeaderChangeDemo Java class will now be initialized in the TestSteps file.

We change the TestSteps file based on the changes in the RequestHeaderChangeDemo Java class.

Public class TestSteps {private final String USER_ID = "(Enter the user id from your test case)"; private Response response; private IRestResponse userAccountResponse; private Product product; private final String BaseUrl = "https://amazon.com"; private RequestHeaderChangeDemo endPoints; @ Given (" ^ User is authorized$ ") public void authorizedUser () {endPoints = new RequestHeaderChangeDemo (BaseUrl); AuthorizationRequest authRequest = new AuthorizationRequest (" (Username) "," (Password) ") EndPoints.authenticateUser (authRequest);} @ Given ("^ Available ProductList $") public void availableProductLists () {IRestResponse productsResponse = endPoints.getProducts (); Product = productsResponse.getBody () .products.get (0);} @ When ("^ Adding the Product in Wishlist$") public void addProductInWishList () {ADDPROD code = new ADDPROD (product.code); AddProductsRequest addProductsRequest = new AddProductsRequest (USER_ID, code) UserAccountResponse = endPoints.addProduct (addProductsRequest);} @ Then ("^ The productis added$") public void productIsAdded () {Assert.assertTrue (userAccountResponse.isSuccessful ()); Assert.assertEquals (201, userAccountResponse.getStatusCode ()); Assert.assertEquals (USER_ID, userAccountResponse.getBody () .UserID); Asert.assertEquals (product.code, userAccountResponse.getBody (). Products.get (0) .code) } @ When ("^ Product to be removed from the list$") public void removeProductFromList () {RemoveProductRequest removeProductRequest = new RemoveProductRequest (USER_ID, product.code); response = endPoints.removeProduct (removeProductRequest);} @ Then ("^ Product is removed$") public void productIsRemoved () {Assert.assertEquals (204, response.getStatusCode ()); userAccountResponse = endPoints.getUserAccount (USER_ID) Assert.assertEquals (200, userAccountResponse.getStatusCode ()); Assert.assertEquals (0, userAccountResponse.getBody (). Products.size ());}}

This is what we did in the modified implementation: code walkthrough

Initialize the RequestHeaderChangeDemo class object as the endpoint.

BaseURL is passed in the first method (that is, authorizedUser).

In the method authorizedUser, we call the constructor authenticateUser of the RequestHeaderChangeDemo class.

Therefore, the next step defines using the same endpoint object.

Modify HTTP request headers using reverse proxies such as browser Mob-Proxy

As the name implies, we can choose to use proxies when handling request header changes in the Java-Selenium automated test suite. Because Selenium forbids injecting information into browsers and servers, you can use proxies for rescue.

This approach is not preferred if the test is performed behind the corporate firewall.

As a component of the Web infrastructure, the agent allows Web traffic to pass through it by positioning itself between the client and the server. In the corporate world, agents work in a similar way, allowing traffic to pass through it, allowing secure traffic to pass through and preventing potential threats. Agents have the ability to partially or completely modify requests and responses.

The core idea is to send authorization headers, bypassing the phase that contains credential conversations, also known as basic authentication dialogues. However, it turns out to be a tiring process, especially when test cases need to be reconfigured frequently.

This is the opportunity for the browser mob-proxy library to display its talents. When you use the agent configuration as part of the Selenium automation test suite, the agent configuration will be valid each time you execute the test suite.

Let's look at how to use the browser mob-proxy with a sample Web site protected by basic authentication. To solve this problem, we may narrow down two possible approaches:

Add authorization headers to all requests with no conditions or exceptions.

Add headers only to requests that meet specific criteria.

Although we will not solve the header management problem, we will demonstrate how to solve the authorization problem with the help of the browser mob-proxy authorization toolset.

In this part of the Selenium Java tutorial, we will focus only on the first approach (that is, adding authorization headers to all requests).

First, we add the dependency of browsermob-proxy to pom.xml

If you want to pass this method to all header requests, that is, specific proxies, in this case, you should call the forAllProxy method, as follows:

Public void forAllProxy () {proxy = new BrowserMobProxyServer (); try {String authHeader = "Basic" + Base64.getEncoder (). EncodeToString ("webelement:click" .getBytes ("utf-8")); proxy.addHeader ("checkauth", authfirstHeader);} catch (UnsupportedEncodingException e) {System.err.println ("the Authorization can not be passed"); e.printStackTrace ();} proxy.start (0) } public class caseFirstTest {WebDriver driver; BrowserMobProxy proxy; @ BeforeAll public static void globalSetup () {System.setProperty ("webdriver.gecko.driver", "(path of the driver)");} @ BeforeEach public void setUp () {setUpProxy (); FirefoxOptions Options = new FirefoxOptions (); Options.setProxy (ClientUtil.createSeleniumProxy (proxy)); driver = new FirefoxDriver (Options) } @ Test public void testBasicAuth () {driver.get ("https://webelement.click/stand/basic?lang=en"); Wait waiter = new FluentWait (driver) .withTimeout (Duration.ofSeconds (50)) .arranging (NoSuchElementException.class); String greetings = waiter.until (ExpectedConditions.visibilityOfElementLocated (By.xpath (" (Mention the xpath) ")) .getText (); Assertions.assertEquals (" (message ")) } @ AfterEach public void tearDown () {if (driver! = null) {driver.quit ();} if (proxy! = null) {proxy.stop ();}} private void setUpProxy ({}}

In the above code, the line that starts with String authHeader indicates that we are creating headers, which will be added to the request. These requests are then passed through the agent we created in proxy.addHeader ("checkauth", authfirstHeader).

Try {String authHeader = "Basic" + Base64.getEncoder (). EncodeToString ("webelement:click" .getBytes ("utf-8")); proxy.addHeader ("checkauth", authfirstHeader);} catch (UnsupportedEncodingException e) {. . . ...} proxy.start (0);}

Finally, we start the agent setting 0 to mark the start parameter, and the agent starts on the port.

Modify the HTTP request header using the Firefox extension

In this part of the Selenium Java tutorial, we will learn how to use the appropriate Firefox browser extension to modify the header request. The main disadvantage of this option is that it is only available for Firefox (not for other browsers such as Chrome, Edge, and so on).

Perform the following steps to modify the HTTP request header using the Firefox extension:

Download the Firefox browser extension

Load the extension.

Set extension preferences.

Set up the required functionality.

Prepare test automation scripts.

Let's take it step by step:

1. Download Firefox browser extension

Use. * xpi to search for the firefox extension and set it in the project

two。 Load Firefox extension

Refer to the following code to add a Firefox configuration file:

FirefoxProfile profile = new FirefoxProfile (); File modifyHeaders = new File (System.getProperty ("user.dir") + "/ resources/modify_headers.xpi"); profile.setEnableNativeEvents (false); try {profile.addExtension (modifyHeaders);} catch (IOException e) {e.printStackTrace ();}

Once we load the Firefox extension into the project, we set the preferences (that is, the various inputs that need to be set before triggering the extension). This is done using the profile.setPreference method.

3. Set extension preferenc

This method sets preferences for any given profile through the keyset parameter mechanism. The first parameter here is the key that sets the value, and the second parameter sets the corresponding integer value.

This is the reference implementation:

Profile.setPreference ("modifyheaders.headers.count", 1); profile.setPreference ("modifyheaders.headers.action0", "Add"); profile.setPreference ("modifyheaders.headers.name0", "Value"); profile.setPreference ("modifyheaders.headers.value0", "numeric value"); profile.setPreference ("modifyheaders.headers.enabled0", true); profile.setPreference ("modifyheaders.config.active", true); profile.setPreference ("modifyheaders.config.alwaysOn", true)

In the above code, we list the number of times we want to set up the header instance.

Profile.setPreference ("modifyheaders.headers.count", 1)

Next, we specify that the header name and header value contain the values that are dynamically received from the API call.

Profile.setPreference ("modifyheaders.headers.action0", "Add")

For the rest of the .setPreference implementation, we enable all so that it allows the extension to be loaded when WebDriver instantiates the Firefox browser and sets the extension to active mode using the HTTP header.

4. Set up the required features

The Desired Capabilities in Selenium is used to set the browser, browser version, and platform type on which automated tests need to be performed.

Here, how do we set up the required features:

DesiredCapabilities capabilities = new DesiredCapabilities (); capabilities.setBrowserName ("firefox"); capabilities.setPlatform (org.openqa.selenium.Platform.ANY); capabilities.setCapability (FirefoxDriver.PROFILE, profile); WebDriver driver = new FirefoxDriver (capabilities); driver.get ("url")

What if you want to modify the HTTP request header using a version of Firefox that is not installed on your local (or test) computer. This is LambdaTest, the largest cloud-based automated testing platform, which provides a faster cross-browser testing infrastructure to save.

With LambdaTest, you have the flexibility to modify HTTP request headers for different browsers and platforms. If you are willing to use the Firefox extension to modify the HTTP request header, you can use LambdaTest to achieve the same function on different versions of Firefox browsers.

5. Draft the entire test automation script

After completing all the above steps, we will continue to design the entire test automation script:

Public void startwebsite () {FirefoxProfile profile = new FirefoxProfile (); File modifyHeaders = new File (System.getProperty ("user.dir") + "/ resources/modify_headers.xpi"); profile.setEnableNativeEvents (false); try {profile.addExtension (modifyHeaders);} catch (IOException e) {e.printStackTrace ();} profile.setPreference ("modifyheaders.headers.count", 1) Profile.setPreference ("modifyheaders.headers.action0", "Add"); profile.setPreference ("modifyheaders.headers.name0", "Value"); profile.setPreference ("modifyheaders.headers.value0", "Numeric Value"); profile.setPreference ("modifyheaders.headers.enabled0", true); profile.setPreference ("modifyheaders.config.active", true); profile.setPreference ("modifyheaders.config.alwaysOn", true); DesiredCapabilities capabilities = new DesiredCapabilities () Capabilities.setBrowserName ("firefox"); capabilities.setPlatform (org.openqa.selenium.Platform.ANY); capabilities.setCapability (FirefoxDriver.PROFILE, profile); WebDriver driver = new FirefoxDriver (capabilities); driver.get ("url") } this is the end of the article on "how to use Selenium WebDriver to modify the HTTP request header in JAVA". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report