使用Android webView访问html页面,碰到ajax跨域访问时,仅仅在header中加入
http { ...... add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Headers X-Requested-With; add_header Access-Control-Allow-Methods GET,POST,OPTIONS; ...... }
信息,无法解决跨域访问问题,可以尝试给webview设置如下配置,已解决该问题;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){ webView.getSettings().setAllowUniversalAccessFromFileURLs(true); }else{ try { Class<?> clazz = webView.getSettings().getClass(); Method method = clazz.getMethod("setAllowUniversalAccessFromFileURLs", boolean.class); if (method != null) { method.invoke(webView.getSettings(), true); } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }