使用shouldInterceptRequest API实现agentWeb的CORS

764 阅读1分钟

更新于2022年3月25日10:05:39

然而发现在有些设备上并不能正常工作


//日期格式化模板
val formatter = SimpleDateFormat("E, dd MMM yyyy kk:mm:ss", Locale.US)

//生成跨域请求
fun buildCORSResponse(): WebResourceResponse {
    val date = Date()
    val dateString = formatter.format(date)
    val headers: Map<String, String> = object : HashMap<String, String>() {
        init {
            put("Connection", "close")
            put("Content-Type", "text/plain")
            put("Date", "$dateString GMT")
            put("Access-Control-Allow-Origin", "*")
            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")
        }
    }
    return WebResourceResponse("text/plain", "UTF-8", 200, "OK", headers, null)
}

//acitvity内实现
class WebActivity: AppCompatActivity(){
    initAgentWeb(url:string="file:///android_asset/index.html"){
         val mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(
                binding.root,
                LinearLayout.LayoutParams(-1, -1)
            )
            .useDefaultIndicator()
            .setAgentWebWebSettings(object : AbsAgentWebSettings(){
                override fun bindAgentWebSupport(agentWeb: AgentWeb?) {
                    agentWeb.let {
                        it?.webCreator?.webView?.settings?.let {
							//设置settings
                        }
                    }
                }
            })
            .setWebViewClient(object : WebViewClient(){
                override fun shouldInterceptRequest(
                        view: WebView?,
                        request: WebResourceRequest?
                    ): WebResourceResponse? {
                        //请求url
                        val urlstr = request?.url?.toString()
                        //请求头
                        val reqHeaders = request?.requestHeaders;
                        val method = request?.method

                        //针对OPTIONS预请求返回特定的response头
                        if (method?.equals("OPTIONS", ignoreCase = true) == true) {
                            return buildCORSResponse();
                        };
                        return null;
                    }
	            }
            })
            .createAgentWeb()
            .ready()
            .go(url)
    }
}

原生安卓webview实现至上述方式类似