How To Modify HTTP Request Headers In JAVA Using Selenium WebDriver?

One of the vital widespread take a look at automation challenges is how will we modify the request headers in Selenium WebDriver. As an automation tester, you’ll come throughout this problem for any programming language, together with Java. Earlier than coming to the answer, we have to perceive the issue assertion higher and arrive at totally different potentialities to change the header request in Java whereas working with Selenium WebDriver.

On this Selenium Java tutorial, we’ll learn to modify HTTP request headers in Java utilizing Selenium WebDriver with totally different out there choices.

So let’s get began!



What are HTTP Headers

HTTP headers are an essential a part of the HTTP protocol. They outline an HTTP message (request or response) and permit the shopper and server to trade optionally available metadata with the message. They’re composed of a case-insensitive header subject identify adopted by a colon, then a header subject worth. Header fields could be prolonged over a number of traces by previous every further line with a minimum of one house or horizontal tab.

Headers could be grouped in accordance with their contexts:

  1. Request Headers: HTTP request headers are used to produce extra details about the useful resource being fetched and the shopper making the request.

  2. Response Headers: HTTP response headers present details about the response. The Location header specifies the situation of a useful resource, and the server header presents details about the server offering the useful resource.

  3. Illustration Headers: HTTP illustration headers are an essential a part of any HTTP response. They supply details about protocol parts like mime sorts, character encodings, and extra. This makes them a significant a part of processing assets over the web.

  4. Payload Headers: HTTP payload headers comprise information concerning the payload of an HTTP message (resembling its size and encoding) however are representation-independent.



Deep Dive Into HTTP Request Headers

The HTTP Request header is a communication mechanism that allows browsers or purchasers to request particular webpages or information from a (Internet) server. When utilized in internet communications or web searching, the HTTP Request Header allows browsers and purchasers to speak with the suitable Internet server by sending requests.

The HTTP request headers describe the request despatched by the net browser to load a web page. It’s additionally known as the client-to-server protocol. The header contains particulars of the shopper’s request, resembling the kind of browser and working system utilized by the person and different parameters required for the correct show of the requested content material on the display screen.

Right here is the key info included inside the HTTP request headers:

  • IP handle (supply) and port quantity.

  • URL of the requested internet web page.

  • Internet Server or the vacation spot web site (host).

  • Knowledge sort that the browser will settle for (textual content, html, xml, and many others.).

  • Browser sort (Mozilla, Chrome, IE) to ship appropriate information.

In response, an HTTP response header containing the requested information is shipped again by the.

Need to take a look at your GameMaker: Studio CSS framework?
Take a look at this Online GameMaker: Studio Testing Cloud, a scalable and reliable web testing cloud for guide and automatic web site testing in GameMaker: Studio.



The Have to Change the HTTP Request Headers

Are you able to guess why we even want to alter the request header as soon as it’s already set into the scripts?

Listed below are among the situations the place you may want to alter the HTTP Request Headers:

  1. Testing the management and/or testing the totally different variants by establishing acceptable HTTP headers.

  2. The necessity to take a look at the circumstances when totally different elements of the net software and even the server logic should be totally examined.

  3. Because the HTTP request headers come to make use of to allow some particular components of an internet software logic, which basically can be disabled in a standard mode, modification of the HTTP request headers could also be required sometimes per the take a look at state of affairs.

Testing the visitor mode on an internet software underneath take a look at is the best case the place you may want to change the HTTP request headers.

Nevertheless, the operate of modifying the HTTP request header, which Selenium RC as soon as supported, is no longer dealt with by Selenium Webdriver.

Because of this the query arises about how we alter the header request when the take a look at automation undertaking is written utilizing the Selenium framework and Java.

For a fast overview on creating a Selenium Check Automation from scratch utilizing Java, Selenium, JUnit 5 and Maven, take a look at the video beneath from LambdaTest YouTube Channel.




How To Modify Header Requests In Selenium Java Undertaking

On this a part of the Selenium Java tutorial, we take a look at the quite a few methods to change header requests in Java. Broadly, there are a number of potentialities, following which one can modify the header request within the Java-Selenium undertaking.

  1. Utilizing a driver/library like REST Assured as an alternative of Selenium.

  2. Utilizing a reverse proxy resembling browser mob-proxy or another proxy mechanism.

  3. Utilizing a Firefox browser extension, which might assist to change the headers for the request.

Allow us to discover every chance one after the other:



Modify HTTP Request Headers Utilizing REST Assured Library

Together with Selenium, we will make use of REST Assured, which is a superb instrument to work with REST providers in a easy approach.

The conditions to configure REST Assured along with your undertaking in any IDE (e.g., Eclipse) is pretty straightforward. After establishing Java, Eclipse, and TestNG, you would want to obtain the required REST Assured jar files.

After the jar information are downloaded, you need to create a undertaking in Eclipse and add the downloaded jar information as exterior jars to the Properties part. That is once more much like the way by which we add Selenium jar information to the undertaking. Upon getting efficiently arrange the Java undertaking with the REST Assured library, you’re good to go.

We intend to create a mechanism in order that the request header is customizable. To attain this with the likelihood talked about above, we first have to know the standard solution to create a request header.

Let’s contemplate the next state of affairs:

  • Now we have one Java class named RequestHeaderChangeDemo the place we preserve the fundamental configurations

  • Now we have a take a look at step file named TestSteps, the place we’ll name the strategies from the RequestHeaderChangeDemo Java class by means of which we’ll execute our take a look at.

Observe the beneath Java class named RequestHeaderChangeDemo.

The BASE_URL is the Amazon web site ( https://www.amazon.com) on which the next 4 strategies are utilized:

  • authenticateUser

  • getProducts

  • addProducts

  • removeProduct

    Within the above Java class file, we’ve got repeatedly despatched the BASE_URL and headers in each consecutive technique. Instance is proven beneath:

    RestAssured.baseURI = BASE_URL;
    RequestSpecification request = RestAssured.given();
    request.header(“Content material-Sort”, “software/json”);
    Response response = request.physique(authRequest).put up(Route.generateToken());

The request.header technique requests the header within the JSON format. There’s a vital quantity of duplication of code which reduces the maintainability facet of the code.

This may be prevented if we initialize the RequestSpecification object within the constructor and make these strategies non-static (i.e. creating the occasion technique).

Because the occasion technique in Java belongs to the Object of the category and to not the category itself, the strategy could be known as even after creating the Object of the category. Together with this, we will even override the occasion technique.

Changing the strategy to an occasion technique ends in the next benefits:

  • Authentication is finished solely as soon as in a single RequestSpecification Object. There gained’t be any additional have to create the identical for different requests.

  • Flexibility to change the request header within the undertaking.

Subsequently, allow us to see how each the Java class RequestHeaderChangeDemo and the take a look at step file TestSteps look once we use the occasion technique.

Java Class for sophistication RequestHeaderChangeDemo with occasion technique

Code Walkthrough

  1. Now we have created a constructor to initialize the RequestSpecification object containing BaseURL and Request Headers.

  2. Earlier, we needed to move the token in each request header. Now, we put the tokenresponse into the identical occasion of the request as quickly as we obtain it within the technique authenticateUser(). This permits the take a look at step execution to maneuver ahead with out including the token for each request prefer it was achieved earlier. This makes the header out there for the following calls to the server.

  3. This RequestHeaderChangeDemo Java class will now be initialized within the TestSteps file.

We modify the TestSteps file according to the modifications within the RequestHeaderChangeDemo Java class.

Code WalkThrough

Right here’s what we’ve got achieved within the modified implementation:

  1. Initiatialized RequestHeaderChangeDemo class objects as endpoints.

  2. The BaseURL was handed within the first technique (i.e. authorizedUser).

  3. Inside the technique authorizedUser, we invoked the constructor authenticateUser of the RequestHeaderChangeDemo class.

  4. Therefore the identical endpoint object is utilized by the following step definitions.



Modify HTTP Request Headers Utilizing Reverse Proxy Like Browser Mob-Proxy

Because the identify suggests, we will go for utilizing proxies when coping with the request header modifications in a Java-Selenium automation take a look at suite. As Selenium forbids injecting info amidst the browser and the server, proxies can come to a rescue.

This method will not be most popular if the testing is being carried out behind a company firewall.

Being an internet infrastructure part, Proxy makes the net site visitors transfer by means of it by positioning itself between the shopper and the server. Within the company world, proxies work equally, making the site visitors move by means of it, permitting those which might be protected and blocking the potential threats. Proxies include the potential to change each the requests and the responses, both partially or utterly.

The core thought is to ship the authorization headers, bypassing the part that features the credential dialogue, often known as the fundamental authentication dialog. Nevertheless, this seems to be a tiring course of, particularly if the take a look at circumstances demand frequent reconfigurations.

That is the place the browser mob-proxy library comes into the image. If you make the proxy configuration a part of the Selenium automation testing suite, the proxy configuration will stand legitimate every time you execute the take a look at suite.

Allow us to see how we will use the browser mob-proxy with a pattern web site that’s secured with fundamental authentication. To deal with this, we’d slim down two potential methods:

  1. Add authorization headers to all requests with no situation or exception.

  2. Add headers solely to the requests which meet sure situations.

Although we won’t handle headers administration issues, we’d nonetheless show the best way to handle authorization points with the assistance of the browser mob-proxy authorization toolset.

On this a part of the Selenium Java tutorial, we’ll focus solely on the primary methodology (i.e. including authorization headers to all of the requests).

First, we add the dependencies of browsermob-proxy in pom.xml

If you wish to move this method to all of the header requests, a specific proxy, on this case, the forAllProxy technique needs to be invoked as proven beneath:

public void forAllProxy()
{
    proxy = new BrowserMobProxyServer();
    attempt {
        String authHeader = "Primary " + Base64.getEncoder().encodeToString("webelement:click on".getBytes("utf-8"));
        proxy.addHeader("checkauth", authfirstHeader);
    }
    catch (UnsupportedEncodingException e)
    {
        System.err.println("the Authorization can't be handed");
        e.printStackTrace();
    }
    proxy.begin(0);
}
Enter fullscreen mode

Exit fullscreen mode

Within the above code, the road that begins with String authHeader states that we’re creating the header, and this will likely be added to the requests. After that, these requests are handed by means of the proxy we created in proxy.addHeader(“checkauth”, authfirstHeader).

attempt {
        String authHeader = "Primary " + Base64.getEncoder().encodeToString("webelement:click on".getBytes("utf-8"));
        proxy.addHeader("checkauth", authfirstHeader);
    }
    catch (UnsupportedEncodingException e)
    {
 ………………………………………………………………………………
 ………………………………………………………………………………
 ……………………………………………………………………………...
    }
    proxy.begin(0);
}
Enter fullscreen mode

Exit fullscreen mode

Ultimately, we begin the proxy setting 0 to mark the beginning parameter, and the proxy begins on the port.

*Need to examine take a look at your Framework7 CSS framework? *

Take a look at this Online Framework7 Testing Cloud, and run automation checks at scale in your Framework7 web site on essentially the most dependable take a look at automation cloud.



Modify HTTP Request Headers Utilizing Firefox Extension

On this a part of the Selenium Java tutorial, we take a look at the best way to modify the header requests utilizing the suitable Firefox browser extension. The key disadvantage of this selection is that it really works solely with Firefox (and never different browsers like Chrome, Edge, and many others.).

Carry out the next steps to change HTTP request headers utilizing a Firefox extension:

  • Obtain the Firefox browser Extension

  • Load the extension.

  • Arrange the extension preferences.

  • Set the Desired Capabilities.

  • Put together the take a look at automation script.

Allow us to undergo every step one after the other:

1. Obtain the Firefox browser Extension

Seek for the firefox extension with .*xpi and set it up within the undertaking

2. Load the Firefox extension

Add the Firefox profile referring to the beneath code:

FirefoxProfile profile = new FirefoxProfile();
File modifyHeaders = new File(System.getProperty("person.dir") + "/assets/modify_headers.xpi");
profile.setEnableNativeEvents(false); 

attempt {
    profile.addExtension(modifyHeaders); 
}
catch (IOException e)
{
    e.printStackTrace();
}
Enter fullscreen mode

Exit fullscreen mode

3. Set the extension preferences

As soon as we load the Firefox extension into the undertaking, we set the preferences (i.e. varied inputs that have to be set earlier than the extension is triggered). That is achieved utilizing the profile.setPreference technique.

This technique units the desire for any given profile by means of the key-set parameter mechanism. Right here the primary parameter is the important thing that units the worth along with the second parameter, which units a corresponding integer worth.

Right here is the reference implementation:

profile.setPreference("modifyheaders.headers.rely", 1);
profile.setPreference("modifyheaders.headers.action0", "Add");
profile.setPreference("modifyheaders.headers.name0", "Worth");
profile.setPreference("modifyheaders.headers.value0", "numeric worth");
profile.setPreference("modifyheaders.headers.enabled0", true);
profile.setPreference("modifyheaders.config.energetic", true);
profile.setPreference("modifyheaders.config.alwaysOn", true);
Enter fullscreen mode

Exit fullscreen mode

Within the above code, we listing the variety of occasions we need to set the header occasion.

profile.setPreference("modifyheaders.headers.rely", 1);
Enter fullscreen mode

Exit fullscreen mode

Subsequent, we specify the motion, and the header identify and header worth comprise the dynamically acquired values from the API calls.

profile.setPreference("modifyheaders.headers.action0", "Add");
Enter fullscreen mode

Exit fullscreen mode

For the remainder of the road of the implementation of .setPreference, we allow all in order that it permits the extension to be loaded when the WebDriver instantiates the Firefox browser together with setting the extension in energetic mode with HTTP header.

4. Arrange the Desired Capabilities

The Desired Capabilities in Selenium are used to set the browser, browser model, and platform sort on which the automation take a look at must be carried out.

Right here we how we will set the specified capabilities:

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");
Enter fullscreen mode

Exit fullscreen mode

What if you wish to modify HTTP request headers with Firefox model which isn’t put in in your native (or take a look at) machine. That is the place LambdaTest, the most important cloud-based automation testing platform that provides sooner cross browser testing infrastructure involves the rescue.

With LambdaTest, you’ve gotten the pliability to change HTTP request headers for various browsers and platform combos. In case you are keen to change HTTP request headers utilizing Firefox extension, you need to use LambdaTest to appreciate the identical on totally different variations of the Firefox browser.

5. Draft the whole take a look at automation script

Upon getting been by means of all of the above steps, we proceed with designing the whole take a look at automation script:

public void startwebsite()
{
    FirefoxProfile profile = new FirefoxProfile();
    File modifyHeaders = new File(System.getProperty("person.dir") + "/assets/modify_headers.xpi");
    profile.setEnableNativeEvents(false); 
    attempt
    {
        profile.addExtension(modifyHeaders); 
    }
    catch (IOException e)
    {
        e.printStackTrace(); 
    }

    profile.setPreference("modifyheaders.headers.rely", 1);
    profile.setPreference("modifyheaders.headers.action0", "Add");
    profile.setPreference("modifyheaders.headers.name0", "Worth");
    profile.setPreference("modifyheaders.headers.value0", "Numeric Worth");
    profile.setPreference("modifyheaders.headers.enabled0", true);
    profile.setPreference("modifyheaders.config.energetic", 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");
}
Enter fullscreen mode

Exit fullscreen mode

*Need a excessive performing cross browser testing and cross gadget testing cloud for at scale Basis CSS testing? *

Right here’s how one can take a look at Foundation CSS Web Apps online and ship pixel good internet expertise irrespective of the gadget.



Conclusion

On this Selenium Java tutorial, we explored three alternative ways to deal with the modifications on the HTTP request headers. Selenium in itself is a good instrument and has constantly labored nicely in internet automation testing.

However, the instrument can not change the request headers. After exploring all of the three alternate options to change the request header in a Java Selenium undertaking, we will vouch for the primary possibility utilizing REST Assured. Nevertheless, you could need to check out the opposite choices and provide you with your observations and perceptions within the feedback part.

Add a Comment

Your email address will not be published. Required fields are marked *