41

How do I get the real device in http_user_agent? When I use a WebView, I can get the real value like this:

[HTTP_USER_AGENT] => Mozilla/5.0(Linux; U; Android 2.2; en-gb; LG-P500 Build/FRF91) 
AppleWebKit/533.0 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

But when I use an Apache connection, the result is different:

[HTTP_USER_AGENT] => Apache-HttpClient/UNAVAILABLE(java 1.4).

What's the problem?

Brad Koch
  • 19,267
  • 19
  • 110
  • 137
user430926
  • 4,017
  • 13
  • 53
  • 77

4 Answers4

75

To complete the accepted answer, if you want the default user agent use System.getProperty("http.agent")

client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
                                System.getProperty("http.agent"));
Maragues
  • 37,861
  • 14
  • 95
  • 96
60

If you don't want to call setHeader() for every request you create you can set the http client parameter CoreProtocolPNames.USER_AGENT. After doing this HTTP client will automatically add this header parameter to each request.

Something like:

client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Custom user agent");

when you create your HttpClient.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
Nic Strong
  • 6,532
  • 4
  • 35
  • 50
13

If you want to set your own user agent header then you have to use the setHeader method.

In case of a HTTP Post request you just set it like this.

private String url = "http://myfancyurl.com/";
private String ua = "My Custom UA Header String";

private HttpPost post = new HttpPost(url);
post.setHeader("User-Agent", ua);

This was just a short explanation how to set a custom user agent string. Your code might look different. The important part is the setHeader method.

Octavian Helm
  • 39,405
  • 19
  • 98
  • 102
  • In this case, i didn't want to set my own user agent. I want it to be automatic like i get in WebView. Is there any solution? Thanks. – user430926 Oct 11 '10 at 08:57
  • Actually you shouldn't use other http clients User Agents, as some server serve different content depending on the user agent (i.e. optimized content for that browser) – Tseng Oct 11 '10 at 09:58
  • Well if you have a special case where you have a service depending on a custom user agent string then there is no way around. – Octavian Helm Oct 11 '10 at 10:57
0

You can read useragent using webview:

new WebView(this).getSettings().getUserAgentString();

Or using system property:

System.getProperty("http.agent")

Source: https://stackoverflow.com/a/50610164/3317927

Grant Miller
  • 27,532
  • 16
  • 147
  • 165