我想在WebView中加载网址并添加标题User-Agent
和autoToken
。
我尝试过val map = HashMap<String, String>()
并将其添加为webview.loadUrl(url, map)
。
第二次尝试只是覆盖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)
}
这些解决方案都不起作用。
答案 0 :(得分:1)
使用以下内容更改User-Agent
webview.getSettings().setUserAgentString("userAgent");
理想情况下,webview.loadUrl(url, map)
应该足以添加标头。通过覆盖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;
}
答案 1 :(得分:1)
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)
应该可以!