UserAgent Based Browser Automation in HtmlUnit

Here is a sample Java code that I tried out for testing the homepage rendering in iPhone3.0 based on user agent.


import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class UserAgent {

  * @param args
 static final WebClient browser;

    static {
     BrowserVersion ff = BrowserVersion.FIREFOX_3_6;
        BrowserVersion version = new BrowserVersion(ff.getApplicationName(), ff.getApplicationVersion(), “Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16”, ff.getBrowserVersionNumeric());
        browser = new WebClient(version);
        browser.setAjaxController(new NicelyResynchronizingAjaxController());
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  HtmlPage currentPage = null;
        try {
         currentPage = (HtmlPage) browser.getPage(““); File(“C:/Users/saikatd/homePage.html”));
        } catch (Exception e) {


I used “User Agent Switcher 0.7.3” Firefox plugin to get the user agent string corresponding to various mobile devices.

This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s