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.
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.
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.
By default this is set to true and the WebView accepts cookies.
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;
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With