Redirecting Browser Through a Proxy in Selenium
Selenium provides a Proxy class to configure browser traffic through a proxy server.
Basic proxy setup:
Java
import org.openqa.selenium.Proxy;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.firefox.FirefoxDriver;
String PROXY = "199.201.125.147:8080";
org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setHttpProxy(PROXY)
.setFtpProxy(PROXY)
.setSslProxy(PROXY);
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(CapabilityType.PROXY, proxy);
WebDriver driver = new FirefoxDriver(cap);
Modern approach with ChromeOptions:
Java
import org.openqa.selenium.Proxy;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chrome.ChromeDriver;
Proxy proxy = new Proxy();
proxy.setHttpProxy("proxy.company.com:8080");
proxy.setSslProxy("proxy.company.com:8080");
ChromeOptions options = new ChromeOptions();
options.setProxy(proxy);
WebDriver driver = new ChromeDriver(options);
driver.get("https://example.com");
SOCKS proxy:
Java
Proxy proxy = new Proxy();
proxy.setSocksProxy("socks.proxy.com:1080");
proxy.setSocksVersion(5);
ChromeOptions options = new ChromeOptions();
options.setProxy(proxy);
Proxy with authentication (ChromeOptions extension):
Java
// For authenticated proxies, pass credentials in the URL
String proxyUrl = "username:password@proxy.server.com:8080";
Proxy proxy = new Proxy();
proxy.setHttpProxy(proxyUrl);
Proxy types supported:
| Method | Protocol |
|---|---|
setHttpProxy() | HTTP traffic |
setSslProxy() | HTTPS/SSL traffic |
setFtpProxy() | FTP traffic |
setSocksProxy() | SOCKS4/5 traffic |
Common use cases:
- ✓Route test traffic through a corporate proxy
- ✓Capture requests via a local proxy (BrowserMob, Charles)
- ✓Test geo-restricted content via regional proxies
- ✓Monitor network calls during test execution
