Android WebView代理设置方法(API10~21适用)
最近碰到个需求需要在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适用)的更多相关文章
- Android WebView的使用方法总结
本文主要讲解WebView的一些常用使用方法 代码如下: xml文件: <LinearLayout xmlns:android="http://schemas.android.com/ ...
- Android webview背景设置为透明无效 拖动时背景闪烁黑色
Adndroid 2.X的设置 webview是一个使用方便.功能强大的控件,但由于webview的背景颜色默认是白色,在一些场合下会显得很突兀(比如背景是黑色). 此时就想到了要把webview的背 ...
- Docker代理设置方法
1.注意Docker版本(此处版本为docker-ce-18.06.1) docker version 2.编辑Docker服务配置文件 vim /usr/lib/systemd/system/doc ...
- android WebView详细使用方法(转)
1.最全面的Android Webview详解 2.最全面总结 Android WebView与 JS 的交互方式 3.你不知道的 Android WebView 使用漏洞 如果想保证登录状态,就插入 ...
- git代理设置方法
客户公司办公,上外网需要代理,临时查一下资料,记录一下: 1.设置代理: git config --global http.proxy http://IP:Port 2.代理设置完成后,查看设置是否生 ...
- Android线程优先级设置方法技巧
对于Android平台上的线程优先级设置来说可以处理很多并发线程的阻塞问题, 比如很多无关紧要的线程会占用大量的CPU时间,虽然通过了MultiThread来解决慢速I/O但是合理分配优先级对于并发编 ...
- Android webView 中loadData方法加载 带中文时出现乱码
WebView出现乱码用LoadData方法来解析html的,但是据说这是官方的一个BUG,不能用来解析中文. 采用loadDataWithBaseURL的方法,其中codeingType设置为utf ...
- android开发(36) Android WebView背景设置为透明
xml布局 <WebView android:id="@+id/wv_content" android:layout_width="match_parent&quo ...
- github for window的代理设置方法
修改 .gitconfig 文件,主要是针对http 和 https进行修改,设置代理 [user] name = name email = mail@.com [http] proxy = 配置文件 ...
随机推荐
- maya user guider第一课,一些基本概念
1.maya主要用于建模,动画, 视觉特效,游戏, 和模拟 一般分为以下几类: l 建模: ploygons, nurbs, subdivision surfaces 这是不同的建模方法. po ...
- maven的安装与配置
1.下载相应版本的maven安装包(压缩文件) http://maven.apache.org/download.cgi 2.环境变量配置 将下载的压缩包解压. 计算机===>属性=====&g ...
- [Golang]Go Packages
---------------------------------------------------------------------------------------------------- ...
- GLib基础
实用功能 GLib中包含了近二十种实用功能,从简单的字符处理到初学者很难理解的XML解析功能,这里介绍两种较简单的:随机数和计时. 下面代码演示如何产生1-100之间的随机整数和演示如何计算30000 ...
- 慕课网-安卓工程师初养成-1-6 MyEclipse的使用简介
来源 http://www.imooc.com/video/1414 http://www.my-eclipse.cn/ MyEclipse 2014 官方版下载地址 声明:MyEclipse 20 ...
- 【练习】手工生成awr报告
①首先进入$ORACLE_HOME/rdbms/admin目录 [oracle@host02 ~]$ cd $ORACLE_HOME/rdbms/admin 该目录下 [oracle@host02 a ...
- django-ajax之post方式
post方式不同于get方式可以被django直接得到,因为django为post加入了csrf保护, 详细的文档地址https://docs.djangoproject.com/en/dev/re ...
- TCP/IP详解学习笔记(14)-- TCP可靠传输的实现
1.概述 为方便描述可靠传输原理,假定数据传输只在一个方向上进行,即A发送数据,B给出确认 2.以字节为单位的滑动窗口 TCP的滑动窗口是以字节为单位的.为了便于说明,字节编号取得 ...
- C# 请求外部服务的办法
) { returnMenuBeizhu = ; ).ToString() borrowT ...
- 【MVC】关于Action返回结果类型的事儿(下)
代码