使用 WebView android代理 配置进行基本方案抢先式代理认证时,
自Android 2.2开始,可以为身份验证设置额外的头部信息。以下代码可以为webView
的http请求添加头部信息:
public void loadUrl(WebView view, String url, String proxyUserName, String proxyPassword){
UsernamePasswordCredentials creds= new UsernamePasswordCredentials(proxyUserName, proxyPassword);
Header credHeader = BasicScheme.authenticate(creds, "UTF-8", true);
Map<String, String> header = new HashMap<String, String>();
header.put(credHeader.getName(), credHeader.getValue());
view.loadUrl(url, header);
}
对于旧版本,可以通过反射在 android.webkit.Network
中设置 mProxyUserName
和 mProxyPassword
以进行抢占式代理身份验证:
public void loadUrl(WebView view, String url, String proxyUserName, String proxyPassword){
try{
Class networkClass = Class.forName("android.webkit.Network");
if (networkClass != null) {
Object networkObj = invokeMethod(networkClass, "getInstance", new Object[]{view.getContext()}, Context.class);
if (networkObj != null) {
Field mProxyUserName = obj.getClass().getDeclaredField("mProxyUserName");
mProxyUserName.setAccessible(true);mProxyUserName.set(networkObj, proxyUserName);
Field mProxyPassword = obj.getClass().getDeclaredField("mProxyPassword");
mProxyPassword.setAccessible(true);mProxyPassword.set(networkObj, proxyPassword);
}
}
}catch(Exception e){
e.printStackTrace();
}
view.loadUrl(url);
}
当您加载一个新的url时,loadUrl()
需要再次调用。这非常重要。
因此,应该使用自定义的 WebViewClient
来覆盖 shouldOverrideUrlLoading(WebView view, String url)
class ProxyAuthWebViewClient extends WebViewClient {
String proxyUserName;
String proxyPassword;
public ProxyAuthWebViewClient(String proxyUserName, String proxyPassword){
this.proxyUserName = proxyUserName;
this.proxyPassword = proxyPassword;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
loadUrl(view, url, proxyUserName, proxyPassword);
return true ;
}
}
同时,在你的webView上设置WebViewClient:
webView.setWebViewClient(new ProxyAuthWebViewClient("user", "password"));
WebViewClient
是最好的实际答案! - MewX