Android Generic User Agent (UA)

Sagar Hatekar picture Sagar Hatekar · Apr 14, 2011 · Viewed 28.3k times · Source

I am building an Android app to display content feed from a server. The server is a mobile website (like http://m.google.com) which tracks the traffic from various mobile clients. To differentiate an Android client, how do I provide a generic string for my app?

Here's why I ask that:

Some of the Android devices I got have UA strings like:

Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; ADR6400L 4G Build/FRG83D) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

Mozilla/5.0 (Linux; U; Android 2.1; en-us; Eclair_SPR Build/30201) AppleWebKit/520.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/520.17

I need to append a string to the UserAgent string to identify my app. For eg:

I need to do something like this: Mozilla/5.0 (Linux; U; Android 2.1; en-us; Eclair_SPR Build/30201) AppleWebKit/520.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/520.17 Android_MyFirstApp.

Is this the correct way to do it?

Answer

Michael Edenfield picture Michael Edenfield · Apr 14, 2011

To change the user agent you need to send a custom User-Agent: header with your HTTP request. Assuming you're using the Android org.apache.http.client.HttpClient class, you have two options:

  1. Set the user agent header on each request. You do this by calling setHeader() on your HttpRequest (HttpPost, HttpGet, whatever) object after you create it:
HttpGet get = new HttpGet(url);
get.setHeader("User-Agent", myUserAgent);
  1. Change the default User Agent parameter, which will affect all future instances of that HttpClient class. You do this by reading the HttpParams collection from your client with getParams() then updating the user agent using setParameter():
DefaultHttpClient http = new DefaultHttpClient(); 
http.getParams().setParameter(CoreProtocolPNames.USER_AGENT, myUserAgent);

If you want to append instead of replace the user agent, you can read the existing one first, change it, and set it back using either of the above methods.

EDIT:

Since you said you're using the WebView view you will need to use the WebSettings customization point there. It's basically the same process. Before you call whichever load() method (loadUrl, loadData, etc) you do set the user agent. The changed user-agent will persist as long as that instance of the WebView is around, so you'd do this in the onCreate() of your Activity:

view = (WebView)findViewById(R.id.webview);
view.getSettings().setUserAgentString(myUserAgent);

Again, if you want to append instead of replace, use getUserAgentString() to read it, then update it and set it back again.