关于android:Android-WebView设置代理及账号密码

29次阅读

共计 1175 个字符,预计需要花费 3 分钟才能阅读完成。

一. 背景

很多小伙伴都会遇到公司的 app 须要通过外网拜访公司的内网服务,这个时候后盾同学就会配置一个代理服务器,app 通过代理服务器拜访公司内网。出于平安的思考,还会对拜访代理服务器的申请进行身份验证。

那么 Android 的 WebView 如何设置代理,之前查了下网上的材料,大多是通过反射进行设置,然而 Google 官网曾经提供了不便的 API 供咱们应用了。所以,上面就简略介绍下 WebView 的代理的设置。

二. 具体步骤

Android WebView 设置代理须要应用 ProxyConfig 相干类,身份验证须要在 WebViewClient 的 onReceivedHttpAuthRequest 里进行。
首先,咱们在我的项目的 build.gradle 增加相干依赖。

implementation 'androidx.webkit:webkit:1.3.0'

设置代理具体代码如下:

private void init() {wv = findViewById(R.id.wv);
    WebSettings webSettings = wv.getSettings();
    webSettings.setSupportZoom(true);
    webSettings.setJavaScriptEnabled(true);
    wv.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm){
            // 身份验证(账号密码)handler.proceed("userName", "password");
        }
    });
    setProxy();
    wv.loadUrl("http://www.uc123.com");
}

private void setProxy() {if (WebViewFeature.isFeatureSupported(WebViewFeature.PROXY_OVERRIDE)) {ProxyConfig proxyConfig = new ProxyConfig.Builder()
                .addProxyRule("111.123.321.121:1234")
                .addDirect().build();
        ProxyController.getInstance().setProxyOverride(proxyConfig, new Executor() {
            @Override
            public void execute(Runnable command) {//do nothing}
        }, new Runnable() {
            @Override
            public void run() {Log.w(TAG, "WebView 代理扭转");
            }
        });
    }
}
正文完
 0