You can use a custom class that inherits from WebView, or if you prefer, you can add an extension function. The logic is essentially the same:
private fun WebView.postUrl(postUrl: String, postData: ByteArray, additionalHttpHeaders: MutableMap<String, String>) {
val savedWebViewClient = getWebViewClient()
webViewClient = object : WebViewClient() {
override fun shouldInterceptRequest(view: WebView, url: String): WebResourceResponse? {
if (url != postUrl) {
view.post {
webViewClient = savedWebViewClient
}
return savedWebViewClient?.shouldInterceptRequest(view, url)
}
Log.d("WebView extension", "post ${postData.decodeToString()} to ${url}")
val httpsUrl = URL(url)
val conn: HttpsURLConnection = httpsUrl.openConnection() as HttpsURLConnection
conn.requestMethod = "POST"
additionalHttpHeaders.forEach { header ->
conn.addRequestProperty(header.key, header.value)
}
conn.outputStream.write(postData)
conn.outputStream.close()
val responseCode = conn.responseCode
Log.d("WebView extension", "responseCode = ${responseCode} ${conn.contentType}")
view.post {
webViewClient = savedWebViewClient
}
// typical conn.contentType is "text/html; charset=UTF-8"
return WebResourceResponse(conn.contentType.substringBefore(";"), "utf-8", conn.inputStream)
}
}
loadUrl(postUrl, additionalHttpHeaders)
}
The code above was redacted for brevity, with most error checking hidden. To work for API below level 26, I use reflection to extract the savedWebViewClient
.
In real life, you also want to override the new shouldInterceptRequest(view: WebView, request: WebResourceRequest)
method, and delegate all other methods of your WebViewClient to the savedWebViewClient
. Probably a PostWithHeadersWebView class (which overrides also setWibViewClient()
) could make your life easier.