Android Generic User Agent (UA)

2020-02-26 07:16发布

问题:

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?

回答1:

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.



回答2:

Since you control your Android client, why don't you create a generic header string, and set it in header every time your app makes a server call? That way you can ensure the string is unique, and can also add any other useful info to be sent to server. You should be able to use webView.loadUrl() to set extra headers.



回答3:

You can totally do that and at developer.android.com suggest it as well, when they talk about the WebView, especially if you want to build a web app for your web view. Reference here: http://developer.android.com/guide/webapps/webview.html

Id suggest not only to keep reference to the application in your User Agent but to also keep track of the version as well.

Anyways, I was looking to change my UA too and the discussions here and the encouraged me to do so as well.

Here is my implementation:

On your Android APP:

String versionName="";
int versionCode=0;
try {
    versionName = getBaseContext().getPackageManager().getPackageInfo(getBaseContext().getPackageName(), 0 ).versionName;
    versionCode = getBaseContext().getPackageManager().getPackageInfo(getBaseContext().getPackageName(), 0 ).versionCode;
} catch (NameNotFoundException e) {
    e.printStackTrace();
}

If you want to auto increment the build number aka. versionCode you may take a look to this other Stack Overflow post as well, the C# solution.

Afterwards you just change the User Agent.

WebView mywebview = (WebView)findViewById(R.id.webView);
String myUserAgent = " MyFancyAPPName  V."+versionName+"."+versionCode;

mywebview.getSettings().setUserAgentString(mywebview.getSettings().getUserAgentString()+myUserAgent);

On your Web Application: In PHP

<?php
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);

if(stripos($ua,'MyFancyAPPName') !== false){
    //do whatever you wish here
}
?>

Or In JavaScript

var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("MyFancyAPPName") > -1;
if(isAndroid) { 
    //do whatever you wish here
}

Or you can directly detect it from the .htaccess file:

RewriteCond %{HTTP_USER_AGENT} ^.*MyFancyAPPName.*$
RewriteRule ^(.*)$ http://www.MyWebSite/MyFancyAPPName [R=301]


回答4:

It depends on what framework you're using to make your requests. If you're using the org.apache classes, you can call setHeader('User-Agent', "Generic user agent here") on the HttpMessage you use to do your request.



回答5:

When you use the web view to access the user-agent, make sure you run the

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

on the UI thread.

If you want to access the user agent in the background thread. use

System.getProperty("http.agent")

To check whether a user-agent is valid or not use this https://deviceatlas.com/device-data/user-agent-tester