android webview google登录授权的时候遇到了这个错误 403: Error: disallowed_useragent
解决方法:
String ua = webview.getSettings().getUserAgentString();
//ua的值等于getUAInfo() 函数获取的值。
webview.getSettings().setUserAgentString(getUAInfo().replace("; wv", ""));
//解决这个问题最关键的地方是,去除UA中的字符串“; wv” 去除成功之后,google授权登录就不会403错误了。
private String getUAInfo() {
String userAgent = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
try {
userAgent = WebSettings.getDefaultUserAgent(this);
} catch (Exception e) {
userAgent = System.getProperty("http.agent");
}
} else {
userAgent = System.getProperty("http.agent");
}
StringBuffer sb = new StringBuffer();
for (int i = 0, length = userAgent.length(); i < length; i++) {
char c = userAgent.charAt(i);
if (c <= '\u001f' || c >= '\u007f') {
sb.append(String.format("\\u%04x", (int) c));
} else {
sb.append(c);
}
}
return sb.toString();
}
//UA字符串里面有 ; wv
Mozilla/5.0 (Linux; Android 9; vivo 1904 Build/PPR1.180610.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/89.0.4389.90 Mobile Safari/537.36
//UA字符串里面无 ; wv
Mozilla/5.0 (Linux; Android 9; vivo 1904 Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/89.0.4389.90 Mobile Safari/537.36
参考资料:
I encountered this issue in Android (and not react). I first started with the solution
web_view.settings.userAgentString = “Mozilla/5.0 (Linux; Android 4.1.1; Galaxy Nexus Build/JRO03C) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19” it worked. However, if the user is not logged in, Google asks the user to login and when they ask the user to verify the login, sometimes on an already logged in device and they report incorrect device details.
Eg: On using the above example I was said I tried logging in on an Android 4 device, even when I was on an Android 9 device. This could be confusing to users.
So I tried seeing what’s the default value in web_view.settings.userAgentString and found the value to be
Mozilla/5.0 (Linux; Android 9; vivo 1904 Build/PPR1.180610.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/89.0.4389.90 Mobile Safari/537.36 I realised the problem is wv in the above string, so I just removed that and it worked fine.
My end code looked something like this
web_view.settings.userAgentString = settings.userAgentString.removeAll("; wv")
|