How to Modify HTTP Request Headers in Selenium WebDriver with Java
This guide explains why and how to change HTTP request headers during Selenium WebDriver automation, covering three practical approaches—using REST‑Assured, employing a BrowserMob proxy, and configuring a Firefox extension—complete with code examples and step‑by‑step instructions.
Why Modify HTTP Request Headers in Selenium Tests?
In automated testing, changing HTTP request headers can be essential for simulating different client conditions, exercising server logic that depends on specific headers, or bypassing authentication mechanisms. Selenium WebDriver does not provide a built‑in way to alter headers, so developers must use work‑arounds.
Three Common Work‑arounds
Use a Java HTTP client library such as REST‑Assured to build requests with custom headers.
Run the browser traffic through a reverse proxy (BrowserMob Proxy) that can inject or modify headers on the fly.
Leverage a Firefox extension (Modify Headers) to set headers directly in the browser.
1. Using REST‑Assured (Java HTTP Framework)
REST‑Assured simplifies the creation of HTTP requests. Below is a simplified RequestHeaderChangeDemo class that demonstrates static methods for authentication, product retrieval, and other API calls.
public class RequestHeaderChangeDemo {
private static final String BASE_URL = "https://****";
public static IRestResponse<Token> 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);
}
// ... other static methods omitted for brevity ...
}The static implementation repeats BASE_URL and header setup for every call, which hurts maintainability. Converting the class to use an instance RequestSpecification eliminates this duplication.
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. " + response);
}
Token token = response.body().jsonPath().getObject("$", Token.class);
request.header("Authorization", "Bearer " + token.token);
}
public IRestResponse<Products> getProducts() {
Response response = request.get(Route.products());
return new RestResponse(Products.class, response);
}
// ... other instance methods ...
}Benefits of the instance approach include a single RequestSpecification per test run and the ability to modify headers dynamically after authentication.
2. Using BrowserMob Proxy (Reverse Proxy)
When Selenium cannot inject headers directly, a proxy can add them to every request. Add the following Maven dependency:
<dependencies>
<dependency>
<groupId>net.lightbody.bmp</groupId>
<artifactId>browsermob-core</artifactId>
<version>2.1.5</version>
<scope>test</scope>
</dependency>
</dependencies>Set up the proxy and inject a custom header:
public void forAllProxy() {
proxy = new BrowserMobProxyServer();
try {
String authHeader = "Basic " + Base64.getEncoder()
.encodeToString("webelement:click".getBytes("utf-8"));
proxy.addHeader("checkauth", authHeader);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
proxy.start(0);
}Configure Selenium to use the proxy:
@BeforeEach
public void setUp() {
setUpProxy();
FirefoxOptions options = new FirefoxOptions();
options.setProxy(ClientUtil.createSeleniumProxy(proxy));
driver = new FirefoxDriver(options);
}This method works well inside corporate firewalls but adds extra infrastructure complexity.
3. Using a Firefox Extension
The "Modify Headers" extension can set custom headers for Firefox‑only test runs. The steps are:
Download the modify_headers.xpi file.
Load the extension into a FirefoxProfile.
Set extension preferences to define header name, value, and action.
Create DesiredCapabilities that include the profile.
Instantiate FirefoxDriver with those capabilities.
Example code for profile configuration:
FirefoxProfile profile = new FirefoxProfile();
File modifyHeaders = new File(System.getProperty("user.dir") + "/resources/modify_headers.xpi");
profile.addExtension(modifyHeaders);
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 caps = new DesiredCapabilities();
caps.setBrowserName("firefox");
caps.setCapability(FirefoxDriver.PROFILE, profile);
WebDriver driver = new FirefoxDriver(caps);After the profile is applied, any request made by the driver will carry the defined header.
Choosing the Right Approach
If you need fine‑grained control and want to avoid extra components, the REST‑Assured instance method is simplest. Use BrowserMob Proxy when you must modify headers for all traffic, especially behind corporate proxies. The Firefox extension is a quick fix for Firefox‑only environments but lacks cross‑browser support.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
