Android - Default user agent for URLConnection?

Enzo Tran picture Enzo Tran · Jan 5, 2013 · Viewed 11k times · Source

I am creating a regular HTTP connection using this code:

URLConnection cn = new URL( "http://...." ).openConnection();
cn.connect();

How do I find out the default user agent for my HTTP connection? I tried using the following codes but they all return null:

Log.d("My app", "User agent = " + cn.getRequestProperties().get("User-Agent"));
Log.d("My app", "User agent = " + cn.getHeaderField("User-Agent"));

Answer

Oleg Vaskevich picture Oleg Vaskevich · Jan 5, 2013

The default user agent is null because the header is empty by default. You will have to set it manually using:

cn.setRequestProperty("User-Agent","your user agent");