When you want to implement HTTP response handling and timeout independently in Android WebView, you may override shouldInterceptRequest and implement HTTP communication independently.
Since it is a sample, it is a rough implementation, but let's say that it is implemented as follows.
override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
val latch = CountDownLatch(1)
var res: InputStream? = null
val call = createOkHttpClient().newCall(Request.Builder().url(request?.url.toString()).method("POST", RequestBody.create(null, "hoge")).build())
call.enqueue(object: Callback {
override fun onFailure(call: Call, e: IOException) {
latch.countDown()
}
override fun onResponse(call: Call, response: Response) {
res = response.body()?.byteStream()
latch.countDown()
}
})
latch.await()
return WebResourceResponse("text/html", "UTF-8",res)
}
private val cookieStore = HashMap<String, MutableList<Cookie>>()
fun createOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.cookieJar(object: CookieJar {
override fun saveFromResponse(url: HttpUrl, cookies: MutableList<Cookie>) {
cookieStore[url.host()] = cookies
}
override fun loadForRequest(url: HttpUrl): MutableList<Cookie> {
val cookies = cookieStore[url.host()]
return cookies ?: ArrayList()
}
})
.build()
}
But be careful when using this. For example, consider the case of getting the following HTML.
<html>
<body>
<script type="text/javascript">
function doPost() {
document.TestForm.submit();
}
</script>
<h1>Test</h1>
<form id="TestForm" name="TestForm" action="http://192.168.100.2:3000/hoge" method="post">
<input type="hidden" name="hoge" value="hogeVal"/>
<input type="hidden" name="fuga" value="fugaVal"/>
<input type="submit" value="submit">
</form>
<script type="text/javascript">
doPost();
</script>
</body>
</html>
Since WebView has an HTML parsing function, the doPost function is called when reading the above HTML, and for the `` `http://192.168.100.2:3000/hoge``` defined in the