setUserAgentString in Android webview has no effect on HTTP header used in loadURL()

岁酱吖の 提交于 2019-12-01 15:08:09

问题


Been trying to change the User-Agent string in the HTTP request of an Android app. I have tested this together with wireshark and the emulator, and have seen that although I set the useragent string in the webview, the associated loadUrl request does not use this user-agent string. Instead I see the Dalvik useragent string in the wireshark capture. Here is the code abstract. Any ideas? Or does the emulator not support this?

@Override
public void run() {
    assert(context != null);

    ...
    ...
    webView = new WebView(context);
    ...
    String defaultUserAgent = "betaUAteststring";


    // Clear per-application caches etc
    webView.clearCache(true);
    webView.clearHistory();
    webView.getSettings().setAppCacheEnabled(false);
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.getSettings().setJavaScriptEnabled(true);


    webView.setWebViewClient(new WebViewClient() {
        @Override  
        public void onPageFinished(WebView view, String url) {
        ....
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
        ..
        }

        @Override
        public void onLoadResource(WebView view, String url) {
        ...
        }
    });


    // Start loading


    webView.getSettings().setUserAgentString(defaultUserAgent);
    String setUA = webView.getSettings().getUserAgentString();
    //--> logging here shows the correct user agent, so the webview does accept the value
    // However the following statement does not result in an http request with the webviews user agent
    webView.loadUrl(url);

    //Alternative doesn't help either (and shouldn't according to javadoc)

    //Map<String,String> headerMap = new HashMap<String,String>();
    //headerMap.put("User-Agent","uaTestInAMap");        
    //webView.loadUrl(url, headerMap);
}

回答1:


Answering my own question. It appears that the emulator for whatever reason is not taking the user agent string from the webview. I have not found out the reason for this however. The code works fine on a real device.




回答2:


You miss to override the default Android behavior on open url (launch default browser). To use your customize browser to navitage, you only have to attach a WebViewClient to WebView

That is achieve adding the following line to your code:

 webView.setWebViewClient(new WebViewClient());

Cheers, Rodrigo



来源:https://stackoverflow.com/questions/13308714/setuseragentstring-in-android-webview-has-no-effect-on-http-header-used-in-loadu

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