Changing HTTP Headers using Fiddler

This post shows how to use Fiddler running on the Selenium nodes to modify the headers based on the tests.

Modifying Fiddler Rules

Fiddler maintains its rules in a CustomRules.js file. This can be accessed from the Fiddler Rules menu > Customize Rules. We can modify this rules file from our Java code to set the desired http header and since Fiddler is acting as the local proxy, it will work for any network connection meaning all browsers.


public static List rulesOnDisk;
public static File file = new File("C:\\Users\\Vinay\\Fiddler2\\Scripts\\CustomRules.js");

@BeforeTest
public void setUp() {
try {
Scanner existingRules = new Scanner(file);
rulesOnDisk = new ArrayList();
while(existingRules.hasNextLine()){
rulesOnDisk.add(existingRules.nextLine());
}
existingRules.close();
PrintStream newRules = new PrintStream(file);
for(String str: rulesOnDisk){
if(str.matches(".*static.*function.*OnBeforeRequest.*")){
String headerName = String.format("oSession.oRequest[\"headerName\"] = \"%s\";", "headerValue");
newRules.println(headerName);
}
newRules.println(str);
}
newRules.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

What the script above is doing is, passing the header name and value to the session request variable. Any request you now make through Chrome, Firefox or actually any browser is going to use this header name and value pair.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s