I.S
I.S

Reputation: 2053

How to load URL with headers in WebView?

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.

Upvotes: 7

Views: 13547

Answers (2)

I.S
I.S

Reputation: 2053

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!

Upvotes: 5

Sagar
Sagar

Reputation: 24947

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;
}

Upvotes: 5

Related Questions