Friday, 11 November 2011

Android - Setting the User Agent for URL connection

By default, the web kit that comes with Android set as user agent the one which tell to the server that it request the mobile version. This information make the server send the mobile version of the URL request, if any.

This property can be changed by setting the property of User agent.

For example, here is the code to emulate our Android phone as a normal Desktop computer and then, receive the normal version of the web page:

URL url = new URL("http://www.google.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
connection.setRequestMethod("GET");

//Emulate the normal desktop connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

InputStream stream = connection.getInputStream();

For more information: Wikipedia - User Agent: http://en.wikipedia.org/wiki/User_agent
Android developers - URLConnection: http://developer.android.com/reference/java/net/URLConnection.html#setRequestProperty(java.lang.String, java.lang.String)
Stack Over Flow - Setting user agent of a Java URL Connection: http://stackoverflow.com/questions/2529682/setting-user-agent-of-a-java-urlconnection

No comments:

Post a Comment