8

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);
}
damcify
  • 91
  • 1
  • 6

2 Answers2

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.

damcify
  • 91
  • 1
  • 6
0

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