Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}
like image 279
damcify Avatar asked Nov 09 '12 13:11

damcify


1 Answers

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.

like image 91
damcify Avatar answered Nov 01 '22 12:11

damcify