android用户代理

Sag*_*kar 51 user-agent android

我正在Android中编写一个使用WebView显示HTML内容的应用程序.有人告诉我为我的应用程序获取Android用户代理 - 我该怎么做?我从我的应用程序以及Android浏览器打开了http://whatsmyuseragent.com - 两个用户代理都是一样的.

请帮忙!

Sag*_*kar 126

经过大量研究,我发现了它.有一种方法可以为Android WebView设置用户代理.

webview.getSettings().setUserAgentString("user-agent-string");
Run Code Online (Sandbox Code Playgroud)

http://developer.android.com/reference/android/webkit/WebSettings.html

  • 如果您加载此网址,您可以对其进行测试:https://www.whoishostingthis.com/tools/user-agent/ 以防万一:D (2认同)

Chr*_*row 12

将此放在java类的onCreate方法中,用于显示WebView的活动:

WebView myWebView = (WebView)findViewById(R.id.webview);
//get the UA of the current running device:
String userAgent = view.getSettings().getUserAgentString() ;
//set the UA of the webview to this value:
myWebView.getSettings().setUserAgentString(userAgent);
Run Code Online (Sandbox Code Playgroud)

不要使用System.getProperty("http.agent") - 这将返回'Dalvik'用户代理(Dalvik是单个Android应用在其中运行的VM)


Mat*_*lis 11

您当前无法为其设置用户代理WebView.

更新 - 我的立场得到纠正!

WebSettings有一个名为setUserAgentString的方法:

webView.getSettings().setUserAgentString("my-user-agent");
Run Code Online (Sandbox Code Playgroud)


Sri*_*thi 5

您可以使用System.getProperty("http.agent")获取默认设备UA.并且webView.getSettings().getUserAgentString();会给你UA的WebView.请注意,我们可以通过编程方式设置UA.所以它可能不是所有情况下的默认设备UA.

System.getProperty("http.agent")获取UA是更好的方法,可以在实例WebView可用之前检索.