最近碰到个需求需要在APP中加入代理,HttpClient的代理好解决,但是WebView碰到些问题,然后找到个API10~API21都通用的类,需要用的同学自己看吧,使用方法,直接调用类方法setProxy即可,applicationName可以设置为null。

 /**
* Created by shengdong.huang on 2015/9/18.
*/
public class ProxySettings { private static final String LOG_TAG = "halfman"; private static final String APPLICATION_NAME = "android.app.Application"; public static boolean setProxy(WebView webview, String host, int port, String applicationName) { // 3.2 (HC) or lower
if (Build.VERSION.SDK_INT <= 13) {
return setProxyUpToHC(webview, host, port);
}
// ICS: 4.0
else if (Build.VERSION.SDK_INT <= 15) {
return setProxyICS(webview, host, port);
}
// 4.1-4.3 (JB)
else if (Build.VERSION.SDK_INT <= 18) {
return setProxyJB(webview, host, port);
}
// 4.4 (KK) & 5.0 (Lollipop)
else {
return setProxyKKPlus(webview, host, port,
applicationName == null ? APPLICATION_NAME : applicationName);
}
} /**
* Set Proxy for Android 3.2 and below.
*/
@SuppressWarnings("all")
private static boolean setProxyUpToHC(WebView webview, String host, int port) {
Log.d(LOG_TAG, "Setting proxy with <= 3.2 API."); HttpHost proxyServer = new HttpHost(host, port);
// Getting network
Class networkClass = null;
Object network = null;
try {
networkClass = Class.forName("android.webkit.Network");
if (networkClass == null) {
Log.e(LOG_TAG, "failed to get class for android.webkit.Network");
return false;
}
Method getInstanceMethod = networkClass.getMethod("getInstance", Context.class);
if (getInstanceMethod == null) {
Log.e(LOG_TAG, "failed to get getInstance method");
}
network = getInstanceMethod.invoke(networkClass, new Object[]{webview.getContext()});
} catch (Exception ex) {
Log.e(LOG_TAG, "error getting network: " + ex);
return false;
}
if (network == null) {
Log.e(LOG_TAG, "error getting network: network is null");
return false;
}
Object requestQueue = null;
try {
Field requestQueueField = networkClass
.getDeclaredField("mRequestQueue");
requestQueue = getFieldValueSafely(requestQueueField, network);
} catch (Exception ex) {
Log.e(LOG_TAG, "error getting field value");
return false;
}
if (requestQueue == null) {
Log.e(LOG_TAG, "Request queue is null");
return false;
}
Field proxyHostField = null;
try {
Class requestQueueClass = Class.forName("android.net.http.RequestQueue");
proxyHostField = requestQueueClass
.getDeclaredField("mProxyHost");
} catch (Exception ex) {
Log.e(LOG_TAG, "error getting proxy host field");
return false;
} boolean temp = proxyHostField.isAccessible();
try {
proxyHostField.setAccessible(true);
proxyHostField.set(requestQueue, proxyServer);
} catch (Exception ex) {
Log.e(LOG_TAG, "error setting proxy host");
} finally {
proxyHostField.setAccessible(temp);
} Log.d(LOG_TAG, "Setting proxy with <= 3.2 API successful!");
return true;
} @SuppressWarnings("all")
private static boolean setProxyICS(WebView webview, String host, int port) {
try
{
Log.d(LOG_TAG, "Setting proxy with 4.0 API."); 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); Class wv = Class.forName("android.webkit.WebView");
Field mWebViewCoreField = wv.getDeclaredField("mWebViewCore");
Object mWebViewCoreFieldInstance = getFieldValueSafely(mWebViewCoreField, webview); Class wvc = Class.forName("android.webkit.WebViewCore");
Field mBrowserFrameField = wvc.getDeclaredField("mBrowserFrame");
Object mBrowserFrame = getFieldValueSafely(mBrowserFrameField, mWebViewCoreFieldInstance); 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); updateProxyInstance.invoke(sJavaBridge, ppcont.newInstance(host, port, null)); Log.d(LOG_TAG, "Setting proxy with 4.0 API successful!");
return true;
}
catch (Exception ex)
{
Log.e(LOG_TAG, "failed to set HTTP proxy: " + ex);
return false;
}
} /**
* Set Proxy for Android 4.1 - 4.3.
*/
@SuppressWarnings("all")
private static boolean setProxyJB(WebView webview, String host, int port) {
Log.d(LOG_TAG, "Setting proxy with 4.1 - 4.3 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 mWebViewCoreFieldInstance = getFieldValueSafely(mWebViewCoreField, webViewClassic); Class wvc = Class.forName("android.webkit.WebViewCore");
Field mBrowserFrameField = wvc.getDeclaredField("mBrowserFrame");
Object mBrowserFrame = getFieldValueSafely(mBrowserFrameField, mWebViewCoreFieldInstance); 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, null));
} catch (Exception ex) {
Log.e(LOG_TAG,"Setting proxy with >= 4.1 API failed with error: " + ex.getMessage());
return false;
} Log.d(LOG_TAG, "Setting proxy with 4.1 - 4.3 API successful!");
return true;
} @SuppressWarnings("all")
private static boolean setProxyKKPlus(WebView webView, String host, int port, String applicationClassName) {
Log.d(LOG_TAG, "Setting proxy with >= 4.4 API."); Context appContext = webView.getContext().getApplicationContext();
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", port + "");
System.setProperty("https.proxyHost", host);
System.setProperty("https.proxyPort", port + "");
try {
Class applictionCls = Class.forName(applicationClassName);
Field loadedApkField = applictionCls.getField("mLoadedApk");
loadedApkField.setAccessible(true);
Object loadedApk = loadedApkField.get(appContext);
Class loadedApkCls = Class.forName("android.app.LoadedApk");
Field receiversField = loadedApkCls.getDeclaredField("mReceivers");
receiversField.setAccessible(true);
ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
for (Object receiverMap : receivers.values()) {
for (Object rec : ((ArrayMap) receiverMap).keySet()) {
Class clazz = rec.getClass();
if (clazz.getName().contains("ProxyChangeListener")) {
Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class);
Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); onReceiveMethod.invoke(rec, appContext, intent);
}
}
} Log.d(LOG_TAG, "Setting proxy with >= 4.4 API successful!");
return true;
} catch (ClassNotFoundException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.v(LOG_TAG, e.getMessage());
Log.v(LOG_TAG, exceptionAsString);
} catch (NoSuchFieldException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.v(LOG_TAG, e.getMessage());
Log.v(LOG_TAG, exceptionAsString);
} catch (IllegalAccessException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.v(LOG_TAG, e.getMessage());
Log.v(LOG_TAG, exceptionAsString);
} catch (IllegalArgumentException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.v(LOG_TAG, e.getMessage());
Log.v(LOG_TAG, exceptionAsString);
} catch (NoSuchMethodException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.v(LOG_TAG, e.getMessage());
Log.v(LOG_TAG, exceptionAsString);
} catch (InvocationTargetException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.v(LOG_TAG, e.getMessage());
Log.v(LOG_TAG, exceptionAsString);
}
return false;
} private static Object getFieldValueSafely(Field field, Object classInstance) throws IllegalArgumentException, IllegalAccessException {
boolean oldAccessibleValue = field.isAccessible();
field.setAccessible(true);
Object result = field.get(classInstance);
field.setAccessible(oldAccessibleValue);
return result;
}
}

就是这些,祝码运昌隆~~

Android WebView代理设置方法(API10~21适用)的更多相关文章

  1. Android WebView的使用方法总结

    本文主要讲解WebView的一些常用使用方法 代码如下: xml文件: <LinearLayout xmlns:android="http://schemas.android.com/ ...

  2. Android webview背景设置为透明无效 拖动时背景闪烁黑色

    Adndroid 2.X的设置 webview是一个使用方便.功能强大的控件,但由于webview的背景颜色默认是白色,在一些场合下会显得很突兀(比如背景是黑色). 此时就想到了要把webview的背 ...

  3. Docker代理设置方法

    1.注意Docker版本(此处版本为docker-ce-18.06.1) docker version 2.编辑Docker服务配置文件 vim /usr/lib/systemd/system/doc ...

  4. android WebView详细使用方法(转)

    1.最全面的Android Webview详解 2.最全面总结 Android WebView与 JS 的交互方式 3.你不知道的 Android WebView 使用漏洞 如果想保证登录状态,就插入 ...

  5. git代理设置方法

    客户公司办公,上外网需要代理,临时查一下资料,记录一下: 1.设置代理: git config --global http.proxy http://IP:Port 2.代理设置完成后,查看设置是否生 ...

  6. Android线程优先级设置方法技巧

    对于Android平台上的线程优先级设置来说可以处理很多并发线程的阻塞问题, 比如很多无关紧要的线程会占用大量的CPU时间,虽然通过了MultiThread来解决慢速I/O但是合理分配优先级对于并发编 ...

  7. Android webView 中loadData方法加载 带中文时出现乱码

    WebView出现乱码用LoadData方法来解析html的,但是据说这是官方的一个BUG,不能用来解析中文. 采用loadDataWithBaseURL的方法,其中codeingType设置为utf ...

  8. android开发(36) Android WebView背景设置为透明

    xml布局 <WebView android:id="@+id/wv_content" android:layout_width="match_parent&quo ...

  9. github for window的代理设置方法

    修改 .gitconfig 文件,主要是针对http 和 https进行修改,设置代理 [user] name = name email = mail@.com [http] proxy = 配置文件 ...

随机推荐

  1. 如何在IIS7上配置 FTP7并使用IIS管理凭据方式进行验证?

    如何在IIS7上配置 FTP7并使用IIS管理凭据方式进行验证? 在 Windows Server 2008 R2 发布后,gOxiA 就开始着手于相关的测试和评估.IIS 是重点测试和评估之一!而今 ...

  2. android L 新控件侧滑菜单DrawerLayout 使用教程

    介绍 drawerLayout是Support Library包中实现了侧滑菜单效果的控件,可以说drawerLayout是因为第三方控件如MenuDrawer等的出现之后,google借鉴而出现的产 ...

  3. 解决Cannot find or open the PDB file问题

    今天使用opencv里的mat想要保存数据里边的像素的平均值和标准差: 但是编程好了之后会出现下面的问题,不能找到pdb file .下面将提供三种解决方法以及产生问题的原因. 程序也运行不出来,整个 ...

  4. Linux逻辑卷管理器(LVM)

    LVM基础 通过使用Linux的逻辑卷管理器(Logical Volume Manager, LVM),用户可以在系统运行时动态调整文件系统的大小,把数据从一块硬盘重定位到另一块硬盘,也可以提高I/O ...

  5. No.002 Add Two Numbers

    Add Two Numbers Total Accepted: 160702 Total Submissions: 664770 Difficulty: Medium You are given tw ...

  6. 华为OJ平台——24点游戏

    题目描述: 给出4个1-10的数字,通过加减乘除,得到数字为24就算胜利 输入: 4个1-10的数字.[数字允许重复,测试用例保证无异常数字]输出: true or false 思路:

  7. The difference between macro and function I/Ofunction comparision(from c and pointer )

    macro is typeless and execute faster than funtion ,becaus of the overhead of calling and returnning ...

  8. Mongodb解决不能连接到服务器的错误

    注:这次解决的这个问题的前提是之前打开MongoDB之后,再次使用的时候无法连接了(使用mongod和mongo都不对) 闲话:遇到这种问题真是让人恼火,所以说句sun of beach,好了~爽 正 ...

  9. 获取本地IP地址信息

    2012-06-05    /// <summary>         /// 获取本地IP地址信息         /// </summary>         void G ...

  10. ajax 的简单应用

    ajax作为前端技术,采用异步方式,根据其采用的方式来讲,不用刷新界面,只是进行数据的传递. 后台还是用servlet的.servlet接收到ajax的get或post请求后.将数据组装成xml或者j ...