Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 647
I.S Avatar asked Jun 15 '18 15:06

I.S


People also ask

How do you intercept a URL in WebView?

setWebViewClient(new WebViewClient() { @Override public void onLoadResource(WebView view, String url) { if (url. startsWith("app://")) { Intent i = new Intent(Intent. ACTION_VIEW, Uri. parse(url), getContext(), Main.

How do I send a post request in WebView?

webView. setWebViewClient(new WebViewClient(){ public void onPageStarted(WebView view, String url, Bitmap favicon) { super. onPageStarted(view, url, favicon); } public boolean shouldOverrideUrlLoading(WebView view, String url) { webView. postUrl(Base_Url, postData.

Do cookies work in WebView?

By default this is set to true and the WebView accepts cookies.


2 Answers

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;
}
like image 108
Sagar Avatar answered Sep 25 '22 19:09

Sagar


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!

like image 32
I.S Avatar answered Sep 23 '22 19:09

I.S