11

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"));
Enzo Tran
  • 5,750
  • 6
  • 31
  • 36

2 Answers2

23

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");
Oleg Vaskevich
  • 12,444
  • 6
  • 63
  • 80
6

With default user agent:

URLConnection cn = new URL("http://....").openConnection();
cn.setRequestProperty("User-agent", System.getProperty("http.agent"));
cn.connect();
defim
  • 456
  • 6
  • 9