1

How can I programmatically set proxy for an Android WebView in API 4.1 and 4.2? For lower versions, the following link helped -

WebView android proxy

Community
  • 1
  • 1
MediumOne
  • 804
  • 3
  • 11
  • 28

2 Answers2

0

This code works -

/**
 * Set Proxy for Android 4.1 and above.
 */
public static boolean setProxyICSPlus(WebView webview, String host, int port, String exclusionList) {

    Log.d("", "Setting proxy with >= 4.1 API.");

    try {

    Class wvcClass = Class.forName("android.webkit.WebViewClassic");
    Class wvParams[] = new Class[1];
    wvParams[0] = Class.forName("android.webkit.WebView");
    Method fromWebView = wvcClass.getDeclaredMethod("fromWebView", wvParams);           
    Object webViewClassic = fromWebView.invoke(null, webview);      

    Class wv = Class.forName("android.webkit.WebViewClassic");
    Field mWebViewCoreField = wv.getDeclaredField("mWebViewCore");
    Object mWebViewCoreFieldIntance = getFieldValueSafely(mWebViewCoreField, webViewClassic);

    Class wvc = Class.forName("android.webkit.WebViewCore");
    Field mBrowserFrameField = wvc.getDeclaredField("mBrowserFrame");
    Object mBrowserFrame = getFieldValueSafely(mBrowserFrameField, mWebViewCoreFieldIntance);

    Class bf = Class.forName("android.webkit.BrowserFrame");
    Field sJavaBridgeField = bf.getDeclaredField("sJavaBridge");
    Object sJavaBridge = getFieldValueSafely(sJavaBridgeField, mBrowserFrame);

    Class ppclass = Class.forName("android.net.ProxyProperties");
    Class pparams[] = new Class[3];
    pparams[0] = String.class;
    pparams[1] = int.class;
    pparams[2] = String.class;
    Constructor ppcont = ppclass.getConstructor(pparams);

    Class jwcjb = Class.forName("android.webkit.JWebCoreJavaBridge");
    Class params[] = new Class[1];
    params[0] = Class.forName("android.net.ProxyProperties");
    Method updateProxyInstance = jwcjb.getDeclaredMethod("updateProxy", params);

    updateProxyInstance.invoke(sJavaBridge, ppcont.newInstance(host, port, exclusionList));

    } catch (Exception ex) {
    Log.e("","Setting proxy with >= 4.1 API failed with error: " + ex.getMessage());
    return false;
    }

    Log.d("", "Setting proxy with >= 4.1 API successful!");
    return true;
}
MediumOne
  • 804
  • 3
  • 11
  • 28
  • @jonney - For older version, check this post - http://stackoverflow.com/questions/4488338/webview-android-proxy. It was mentioned in the question. :-) – MediumOne Jul 04 '13 at 05:56
0

This is the complete way to set proxy for WebView. You should set proxy accordingly for each SDK version. Avoid not posting soooo much code, please have a look at this github page

https://github.com/androidyue/DroidWebViewProxyDemo/blob/master/app/src/main/java/com/droidyue/proxydemo/ProxyUtils.java

Hope this could help you.

androidyue
  • 952
  • 10
  • 11