UserAgent Based Browser Automation in HtmlUnit

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

import java.io.File;

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.setJavaScriptEnabled(false);
        browser.setRedirectEnabled(true);
        browser.setAjaxController(new NicelyResynchronizingAjaxController());
    }
   
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  HtmlPage currentPage = null;
        try {
         currentPage = (HtmlPage) browser.getPage(“http://www.amazon.com“);
         currentPage.save(new File(“C:/Users/saikatd/homePage.html”));
        } catch (Exception e) {
            e.printStackTrace();
        }
 }

}

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

Advertisements
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:

WordPress.com Logo

You are commenting using your WordPress.com 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