7

I want to load a URL in a WebView and add headers User-Agent and autoToken. I have tried to just have val map = HashMap<String, String>() and add it as webview.loadUrl(url, map).

The second try was to just override shouldInterceptRequest().

override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest): WebResourceResponse? {
    request.requestHeaders?.put(LegacyAuthInterceptor.HEADER_AUTH_TICKET, autoToken)
   request.requestHeaders?.put("User-Agent", userAgent)
    return super.shouldInterceptRequest(view, request)
  }

None of these solutions are working.

TofferJ
  • 4,678
  • 1
  • 37
  • 49
I.S
  • 1,904
  • 2
  • 25
  • 48

2 Answers2

5

Use following for changing User-Agent

webview.getSettings().setUserAgentString("userAgent");

Ideally webview.loadUrl(url, map) should suffice to add the headers. Following in another alternative by overriding methods in WebViewClient:

@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request){
    view.loadUrl(request.getUrl().toString(),headerMap);
    return true;
}

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
    view.loadUrl(url,headerMap);
    return true;
}
Sagar
  • 23,903
  • 4
  • 62
  • 62
  • This solution worked for me. In my case, the page requires access token, I needed to put authorization token on every request from either `loadUrl(String, Map)` of Android's WebView and ```submit``` of Form in HTML. – iroiroys Oct 06 '21 at 11:14
4
val map = HashMap<String, String>()
map[AUTO_TOKEN] = autoToken
webClientBinding.webView.settings.userAgentString = userAgent
WebView.setWebContentsDebuggingEnabled(true)
webClientBinding.webView.webViewClient = object : WebViewClient() {
  override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest): WebResourceResponse? {
    CookieManager.getInstance().removeAllCookies(null)
    return super.shouldInterceptRequest(view, request)
  }
}
webClientBinding.webView.loadUrl(url, map)

It should work!

I.S
  • 1,904
  • 2
  • 25
  • 48