为ICS和JellyBean设置Android WebView代理

时间:2013-01-09 11:42:30

标签: android android-webview

如何在API 4.1和4.2中以编程方式为Android WebView设置代理?对于较低版本,以下链接有帮助 -

WebView android proxy

2 个答案:

答案 0 :(得分:0)

此代码有效 -

/**
 * 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;
}

答案 1 :(得分:0)

这是为WebView设置代理的完整方法。您应该为每个SDK版本相应地设置代理。 避免不发布太多代码,请看一下这个github页面

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

希望这可以帮到你。