led*_*edy 19 android webview cors
Android是否允许本机应用程序禁用http://(非本地/文件)请求的CORS安全策略?
在我的原生应用程序中,webview通过http://显示远程html,而不是本地/文件系统.这似乎与网络浏览器中的CORS限制相同.
Worakround:ajax请求跨域的native-js桥接器Access-Control-Allow-Origin: *是我的quick'n'irt解决方案.(jsonp或服务器端代理不是一个选项,因为web服务检查客户端的cookie + ip.)
是否可以针对inapp网络视图禁用此政策?
请告诉我,如果有一个简单的标志允许js绕过这个限制,这限制了"原生"应用程序的webview.
dav*_*oli 11
从Android API级别21开始,现在可以这样做。您可以像下面这样创建OPTIONS响应:
public class OptionsAllowResponse {
static final SimpleDateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy kk:mm:ss", Locale.US);
@TargetApi(21)
static WebResourceResponse build() {
Date date = new Date();
final String dateString = formatter.format(date);
Map<String, String> headers = new HashMap<String, String>() {{
put("Connection", "close");
put("Content-Type", "text/plain");
put("Date", dateString + " GMT");
put("Access-Control-Allow-Origin", /* your domain here */);
put("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
put("Access-Control-Max-Age", "600");
put("Access-Control-Allow-Credentials", "true");
put("Access-Control-Allow-Headers", "accept, authorization, Content-Type");
put("Via", "1.1 vegur");
}};
return new WebResourceResponse("text/plain", "UTF-8", 200, "OK", headers, null);
}
}
Run Code Online (Sandbox Code Playgroud)
然后从您的WebViewClient实现中调用它,如下所示:
@Override
@TargetApi(21)
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
return OptionsAllowResponse.build();
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
这仅适用于API级别21,因为OPTIONS响应需要从WebResourceRequest检查请求的HTTP方法,该方法仅从API 21开始可用。
| 归档时间: |
|
| 查看次数: |
21491 次 |
| 最近记录: |