Access-Control-Allow-Origin Error At Android 4.1

2019-01-08 19:12发布

I have problems with Access-Control-Allow-Origin at Android 4.1

In my application i have some local HTML files and Javascripts which i was using to fetch data from web services. Until trying Android 4.1 there was no problem but after trying at Android 4.1 i got this error.

I read lots of documents but i couldn't find a way to solve this problem.

3条回答
欢心
2楼-- · 2019-01-08 19:29

@I am Developer and the others who are facing the same problem.

Slushis solution works fine. But if you want to compile against and support systems below API11 you have to add the following:

if (Build.VERSION.SDK_INT >= 16) {  
    Class<?> clazz = webView.getSettings().getClass();
    Method method = clazz.getMethod("setAllowUniversalAccessFromFileURLs", boolean.class);
    if (method != null) {
        method.invoke(webView.getSettings(), true);
    }
}

This will load and invoke the method at runtime, so you can compile with e.g. Android 2.3.3.

查看更多
老娘就宠你
3楼-- · 2019-01-08 19:43

you need to do something like

if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) 
  wv.getSettings().setAllowUniversalAccessFromFileURLs(true);
查看更多
老娘就宠你
4楼-- · 2019-01-08 19:51

Are your web services hosting from the same domain ? I used to get this error while making an ajax call to a service under a different domain. If you have control on the web service, you can set Access-Control-Allow-Origin: * in the header, (although this way is not a secure way of doing so.)

查看更多
登录 后发表回答