BrowserMob proxy allows you to manipulate HTTP requests and responses, capture HTTP content, and export performance data as a HAR file.
Add below maven dependency to your pom.xml in the project.
<dependency>
<groupId>net.lightbody.bmp</groupId>
<artifactId>browsermob-core</artifactId>
<version>2.1.5</version>
</dependency>
Start a browermob server.
public BrowserMobProxyServer proxy;
public BrowserMobProxyServer getProxyServer() {
proxy = new BrowserMobProxyServer();
proxy.setTrustAllServers(true);
// above line is needed for application with invalid certificates
proxy.start();
return proxy;
}
Stop a browermob server.
public void stopProxyServer() {
if (proxy != null) {
proxy.stop();
}
}
Set browsermob proxy with selenium proxy object.
public Proxy getSeleniumProxy() throws MyException {
getProxyServer();
// get the Selenium proxy object - org.openqa.selenium.Proxy;
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
try {
String hostIp = Inet4Address.getLocalHost().getHostAddress();
seleniumProxy.setHttpProxy(hostIp + ":" + proxy.getPort());
seleniumProxy.setSslProxy(hostIp + ":" + proxy.getPort());
} catch (Exception e) {
throw new MyException(e.getMessage());
}
return seleniumProxy;
}
Set proxy object with Chrome Options.
public ChromeOptions proxyChromeOptions() throws MyException {
ChromeOptions chromeOptions = new ChromeOptions();
try {
// set proxy object with chromeoption
chromeOptions.setProxy(getSeleniumProxy());
} catch (Exception e) {
throw new MyException(e.getMessage());
}
return chromeOptions;
}
Set proxy object with Firefox Options.
public FirefoxOptions proxyFirefoxOptions() throws MyException {
FirefoxOptions firefoxOptions = new FirefoxOptions();
try {
// set proxy object with Firefox option
firefoxOptions.setProxy(getSeleniumProxy());
} catch (Exception e) {
throw new MyException(e.getMessage());
}
return firefoxOptions;
}
Set proxy object with Edge Options.
public EdgeOptions proxyEdgeOptions() throws MyException {
EdgeOptions edgeOptions = new EdgeOptions();
try {
// set proxy object with chromeoption
edgeOptions.setProxy(getSeleniumProxy());
} catch (Exception e) {
throw new MyException(e.getMessage());
}
return edgeOptions;
}
Enable har logs.
public void enableHar(String harLogName) {
proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
// create a new HAR with the label (EX:APP Testing)
proxy.newHar(harLogName);
}
Write har details in har file.
public void getHarData(String filePath) throws MyException {
try {
// get the HAR data
Har har = proxy.getHar();
// Write HAR Data in a File (C:\\networklog.har)
File harFile = new File(filePath);
har.writeTo(harFile);
} catch (Exception e) {
throw new MyException(e.getMessage());
}
}
What is HAR -HTTP Archive format or HAR is a JSON-formatted archive file format for logging of a web browser's interaction with a web application.
To view the HAR file download the HTTP Archive Viewer chrome addon.
No comments:
Post a Comment