How to load URL with headers in WebView?

耗尽温柔 提交于 2020-08-07 06:48:11

问题


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.


回答1:


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



回答2:


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!



来源:https://stackoverflow.com/questions/50878560/how-to-load-url-with-headers-in-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!