27

I want to use the default user agent for the phone in a HttpClient connection and would like to know if there is a way to obtain the user agent without having to have a WebView to query.

Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110
cottonBallPaws
  • 21,220
  • 37
  • 123
  • 171

3 Answers3

53

Very late answer, for others that may be looking for this.

I was looking for a way to obtain the user agent string used by HttpUrlConnection, to use it with HttpClient and amend it with my own version info. This way, my Android app provides some useful version info I can extract from the server's log files (Android Version, device name/type, and the version of my app).

For example, the user agent string for my phone when using HttpUrlConnection looks like this:

Dalvik/1.4.0 (Linux; U; Android 2.3.5; HTC Desire HD A9191 Build/GRJ90)

This string can be obtained from system properties like so:

String userAgent = System.getProperty( "http.agent" );
Stefan Frye
  • 2,007
  • 1
  • 20
  • 24
14

Starting from API level 17 there is a static method in WebSettings which returns the default User-Agent string used by a WebView:

WebSettings.getDefaultUserAgent(context)

Since the method is static you don't need a WebView instance to run it.

Volo
  • 28,673
  • 12
  • 97
  • 125
0

No, this is afaik the only official way to get user agent string.

Btw, the string returned is something like this:

Mozilla/5.0 (Linux; U; Android 1.1; en-gb; dream) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2 – G1 Phone

Http servers use user agent string to serve browser-specific versions of documents. This would only make sense if you want a mobile version of some page and/or if you want to display this later in Android's browser.

Peter Knego
  • 79,991
  • 11
  • 123
  • 154