1、重写WebViewClient 的 shouldInterceptRequest(),拦截请求,实现特殊处理(跨域处理)。
例如:拦截旧的url,替换域名,替换参数等,然后使用新url重新发起请求。
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldInterceptRequest(
view: WebView,
request: WebResourceRequest
): WebResourceResponse? {
request.url.toString().let {
// 判断该请求是否需要拦截处理
if (it.contains("xxx")) {
return assembleResponse(view, request)
}
}
//此处代表拦截器不处理该请求,直接原路请求器处理
return super.shouldInterceptRequest(view, request)
}
2、组装WebResourceResponse:文章来源:https://www.toymoban.com/news/detail-551912.html
/**
* 手动组装response
*/
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private fun assembleResponse(
view: WebView,
request: WebResourceRequest
): WebResourceResponse? {
try {
val originUrl = request.url.toString()
val realUrl = getRealUrl(originUrl)
// val headers = request.requestHeaders
val response = doGet(realPath, null).execute()
if (response.isSuccessful && response.code() == 200) {
return response.body()?.run {
WebResourceResponse(
response.header("Content-Type"),
response.header("Content-Encoding"),
response.body()?.byteStream()
)
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
3、网络请求–Get:文章来源地址https://www.toymoban.com/news/detail-551912.html
private fun addHeader(builder: Request.Builder, headers: JSONObject?) {
if (headers != null) {
val keys = headers.keys()
while (keys.hasNext()) {
val key = keys.next()
val value = headers.optString(key, "")
builder.addHeader(key, value)
}
}
}
fun doGet(url: String?, headers: JSONObject?): Call? {
var client: OkHttpClient? = null
val trustManager = HttpUtils.getX509TrustManager()
val okhttpBuilder = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS) // okhttp 已经有RetryAndFollowUpInterceptor
.hostnameVerifier(HttpUtils.TrustAllHostnameVerifier())
.addNetworkInterceptor(RemoveDirtyConnIntercepter())
.sslSocketFactory(SSLSocketFactoryCompat(trustManager), trustManager)
client = okhttpBuilder.build()
val builder = Request.Builder().url(url)
addHeader(builder, headers)
val request = builder.get()
.build()
return client.newCall(request)
}
到了这里,关于Android webview拦截请求,实现跨域处理的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!