一般Web浏览器在访问各个网站时,会在HTTP请求的Header里设置User-Agent字段,表示请求者的身份信息,比如在我华为U9200的Android手机上,打开Chrome浏览器后,每个访问请求的User-Agent字段如下:
?
Mozilla/5.0 (Linux; Android 4.0.3; U9200 Build/HuaweiU9200)
对于安卓App来说,默认情况下的HTTP请求Header是不会带上这么一串字符串的。如果要带必须得自己构造了,我摸索了半天,还是找到了达到和浏览器同样格式的设置User-Agent的方法:
?
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
// HttpPost httpPost = new HttpPost(url); // 如果是POST请求,则改为注释掉上面一行
// MY_APP_NAME为APP名称,MY_APP_VERSION_NAME为应用的版本名
httpGet.setHeader("User-Agent", String.format("%s/%s (Linux; Android %s; %s Build/%s)", MY_APP_NAME, MY_APP_VERSION_NAME, Build.VERSION.RELEASE, Build.MANUFACTURER, Build.ID));
Mozilla/5.0 (Linux; Android 4.0.3; U9200 Build/HuaweiU9200)
对于安卓App来说,默认情况下的HTTP请求Header是不会带上这么一串字符串的。如果要带必须得自己构造了,我摸索了半天,还是找到了达到和浏览器同样格式的设置User-Agent的方法:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
// HttpPost httpPost = new HttpPost(url); // 如果是POST请求,则改为注释掉上面一行
// MY_APP_NAME为APP名称,MY_APP_VERSION_NAME为应用的版本名
httpGet.setHeader("User-Agent", String.format("%s/%s (Linux; Android %s; %s Build/%s)", MY_APP_NAME, MY_APP_VERSION_NAME, Build.VERSION.RELEASE, Build.MANUFACTURER, Build.ID));