最近碰到个需求需要在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. gcc编译, gdb调试, makefile写法

    //test.c: #include <stdio.h> int main(void) { printf("hello world!"); return 0; } == ...

  2. FPS学习记录

    最近在网上查了一些FPS的相关知识,在此和大家一起分享.FPS(Frames Per Second):每秒传输帧数,它是图像领域中的一个术语. Frames Per Second更确切的解释是“每秒中 ...

  3. Java注解(Annotation)自定义注解入门

    要深入学习注解,我们就必须能定义自己的注解,并使用注解,在定义自己的注解之前,我们就必须要了解Java为我们提供的元注解和相关定义注解的语法. 元注解: 元注解的作用就是负责注解其他注解.Java5. ...

  4. SDUT 2141 【TEST】数据结构实验图论一:基于邻接矩阵的广度优先搜索遍历

    数据结构实验图论一:基于邻接矩阵的广度优先搜索遍历 Time Limit: 1000MS Memory Limit: 65536KB Submit Statistic Discuss Problem ...

  5. python中get、post数据

    方法一:urllib2 参考:http://www.cnblogs.com/chenzehe/archive/2010/08/30/1812995.html post: #!/usr/bin/pyth ...

  6. 洛谷P1470 最长前缀 Longest Prefix

    P1470 最长前缀 Longest Prefix 73通过 236提交 题目提供者该用户不存在 标签USACO 难度普及/提高- 提交  讨论  题解 最新讨论 求大神指导,为何错? 题目描述 在生 ...

  7. MySQL学习笔记(二)

    二.SQL基本知识 SQL 是一种典型的非过程化程序设计语言,这种语言的特点是:只指定哪些数据被操纵,至于对这些数据要执行哪些操作,以及这些操作是如何执行的,则未被指定.非过程化程序设计语言的优点在于 ...

  8. dll延迟加载

    用于隐式链接选项, 这样设置后在exe调用dll的函数才会加载dll,调用DLL_PROCESS_ATTACH.否则隐式链接直接会在exe启动时加载dll

  9. haproxy配置文件简单管理

    版本:python3功能:对haproxy配置文件进行简单的查询.添加以及删除功能操作流程:1.根据提示选择相应的选项2.进入所选项后,根据提示写入相应的参数3.查询功能会返回查询结果,添加.删除以及 ...

  10. 二模11day1解题报告

    T1.树的重量(weight) 给出一棵n个叶节点的树(但是有多组数据)以及n个节点之间的距离(最短距离...然而也只有一条路),求树的所有边权之和. 一开始完全没有思路啊...难道爆搜模拟??狂汗. ...