Android webview add header to each request without using shouldInterceptRequest

758 Views Asked by At

I want to add my header to each request in webview but I dont want recreate the request using OkHttp or DefaultHttpClient since WebResourceRequest from shouldInterceptRequest does not return the request body so my POST requests wont have value when i send it.

I tried adding my header inside shouldInterceptRequest but i doesnt work properly seems its not adding on each request.

  override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
            request?.requestHeaders?.clear()
            request?.requestHeaders?.apply {
                put("header", "value") 
            }
            return super.shouldInterceptRequest(view, request)
        }
1

There are 1 best solutions below

1
D Ta On

Can you try passing the header values via the view: WebView param using:

public void loadUrl(@NonNull String url, @NonNull Map<String, String> additionalHttpHeaders) {

so something like:

  override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
    view.loadUrl("your url", mapOf("header" to "value"))
    return super.shouldInterceptRequest(view, request)
  }