Pages

2010-04-12

Providing for mobile web site visitors

When I'm using a mobile or an iPod Touch the web sites that detect my device and show me a mobile friendly page are more likely to be added to my favourites. For example Digg has a mobile version of their site which you are automatically taken to.

You can detect a mobile device by looking at the HTTP User Agent and Accept headers. Here are these two headers for an Android phone as captured in my application log:
INFO: Mozilla/5.0 (Linux; U; Android 1.5; en-gb; T-Mobile_G2_Touch Build/CUPCAKE) AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1
INFO: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5,application/youtube-client
and for an iPod Touch:
INFO: Mozilla/5.0 (iPod; U; CPU iPhone OS 3_1_3 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7E18 Safari/528.16
INFO: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Detecting all the many and varied mobile devices out there would be a real pain without the help of MobileESP. This project supports multiple languages but I'm using Java on Google App Engine so all I needed to do was place the single java source file in my project.

I then wrote a servlet to handle requests to the home URL which redirects to the normal or mobile version of the site like so:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    String userAgent = req.getHeader("User-Agent");
    String accept = req.getHeader("Accept"); 
     
    UAgentInfo info = new UAgentInfo(userAgent, accept);
       
    boolean iPhone = info.detectTierIphone();
          
    if (iPhone) {
        res.sendRedirect("/Mobile.html");
    } else {
        res.sendRedirect("/Normal.html");
    }
} 
This code simply passes the headers to the UAgentInfo object and then detects iPhone like devices. The Javadoc for detectTierIphone() says:
The quick way to detect for a tier of devices. This method detects for devices which can display iPhone-optimized web content. Includes iPhone, iPod Touch, Android, Palm WebOS, etc.

No comments:

Post a Comment