Android WebView跨域

实现原理:重写WebViewClient中shouldInterceptRequest方法,在Response中添加header达到跨域的作用;

@Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String urlstr) {
            try {
                // Our implementation just parses the response and visualizes it. It does not properly handle
                // redirects or HTTP errors at the moment. It only serves as a demo for intercepting POST requests
                // as a starting point for supporting multiple types of HTTP requests in a full fletched browser
                URL url = null;
                String fileExtens =null;
                if (isProxyUrl) {
                    fileExtens = MimeTypeMap.getFileExtensionFromUrl(urlstr);
                }else{
                    url=new URL(urlstr);
                }
                if (TextUtils.isEmpty(fileExtens)){
                    fileExtens="html";
                }
                String mimeType = FileStreamType.getStreamType(fileExtens);
                if (isProxyUrl) {
                    url = new URL(generateProxyUrl(urlstr,mimeType));
                }
                URLConnection rulConnection = url.openConnection();
                HttpURLConnection conn = (HttpURLConnection) rulConnection;
                conn.setRequestProperty("contentType", mimeType);
                conn.setRequestProperty("Accept", mimeType);
                conn.setRequestProperty("Accept-Charset", "utf-8");
                conn.setRequestMethod("GET");
                    String encodeing =conn.getContentEncoding();
                    if(TextUtils.isEmpty(encodeing)){
                        encodeing="utf-8";
                    }
                WebResourceResponse webResourceResponse= new WebResourceResponse(mimeType,encodeing, conn.getInputStream());
                Map<String,String> headers=new HashMap<>();
                // 解决webView跨域问题
                headers.put("Access-Control-Allow-Origin", ApiPath.getInstance().getHostName());
                headers.put("Access-Control-Allow-Headers","X-Requested-With");
                headers.put("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE");
                headers.put("Access-Control-Allow-Credentials", "true");
                webResourceResponse.setResponseHeaders(headers);
                return webResourceResponse;
//                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值