public void changeProxySettings(String host, int port){ if(Build.VERSION.SDK_INT > 14 && Build.VERSION.SDK_INT < 20){ changeProxyWithLikProperties(String host, int port); }else if(Build.VERSION.SDK_INT > 20 && Build.VERSION.SDK_INT < 23){ changeProxyWithProxyInfo(String host, int port); }else{ throw new Exception("Sorry, android version not supported") } }
@RunWith(AndroidJUnit4.class) public class WifiProxyChangerTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Rule public ActivityTestRule mActivityRule = new ActivityTestRule<>( MainActivity.class); Context context; @Before public void prepare() throws Exception { context = mActivityRule.getActivity(); ExceptionsPreparer.prepareExceptions(expectedException, context); } @Test public void testChangeWifiStaticProxySettings() throws Exception { String testIp = RandomValuesGenerator.randomIp(); int testPort = RandomValuesGenerator.randomPort(); WifiProxyChanger.changeWifiStaticProxySettings(testIp, testPort, context); assertEquals(testIp, WifiProxyInfo.getHost(context)); assertEquals(testPort, WifiProxyInfo.getPort(context)); } @Test public void testProxySettingsClear() throws Exception { String testIp = RandomValuesGenerator.randomIp(); int testPort = RandomValuesGenerator.randomPort(); WifiProxyChanger.changeWifiStaticProxySettings(testIp, testPort, context); WifiProxyChanger.clearProxySettings(context); assertEquals(ProxySettings.NONE, CurrentProxyChangerGetter .chooseProxyChangerForCurrentApi(context) .getProxySettings()); } @After public void learSettings() throws Exception { if (NetworkHelper.isWifiConnected(context) && ApiChecker.isSupportedApi()) WifiProxyChanger.clearProxySettings(context); } }
@RunWith(AndroidJUnit4.class) public class WifiProxyInfoTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Rule public ActivityTestRule mActivityRule = new ActivityTestRule<>( MainActivity.class); Context context; @Before public void prepareAndPresetProxy() throws Exception { context = mActivityRule.getActivity(); ExceptionsPreparer.prepareExceptions(expectedException, context); if (ApiChecker.isSupportedApi()) { WifiProxyChanger.clearProxySettings(context); WifiProxyChanger.changeWifiStaticProxySettings("localhost", 3030, context); } } @Test public void testGetHost() throws Exception { assertEquals("localhost", WifiProxyInfo.getHost(context)); } @Test public void testGetPort() throws Exception { assertEquals(3030, WifiProxyInfo.getPort(context)); } @Test public void testGetProxySettings() throws Exception { assertEquals(ProxySettings.STATIC, WifiProxyInfo.getProxySettings(context)); } @After public void learSettings() throws Exception { if (NetworkHelper.isWifiConnected(context) && ApiChecker.isSupportedApi()) WifiProxyChanger.clearProxySettings(context); } }
@RunWith(AndroidJUnit4.class) public class CurrentProxyChangerGetterTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Rule public ActivityTestRule mActivityRule = new ActivityTestRule<>( MainActivity.class); Context context; @Before public void prepare() throws Exception { context = mActivityRule.getActivity(); ExceptionsPreparer.prepareExceptions(expectedException, context); } @Test public void testChooseProxyChangerForCurrentApi() throws Exception { ProxyChanger proxyChanger = CurrentProxyChangerGetter.chooseProxyChangerForCurrentApi(context); WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); assertEquals(manager.getConnectionInfo().getNetworkId(), proxyChanger.getWifiConfiguration().networkId); if (ApiChecker.isJellyBeanOrKitkat()) { assertTrue(proxyChanger instanceof WifiConfigurationForApiFrom15To19); } else if (ApiChecker.isLolipop()) { assertTrue(proxyChanger instanceof WifiConfigurationForApiFrom21To22); } } }
public abstract class ExceptionsPreparer { public static void prepareExceptions(ExpectedException expectedException, Context context) throws Exception { if (!ApiChecker.isSupportedApi()) { expectedException.expect(ApiNotSupportedException.class); } else if (!NetworkHelper.isWifiConnected(context)) { expectedException.expect(NullWifiConfigurationException.class); } else if (!CurrentProxyChangerGetter.chooseProxyChangerForCurrentApi(context).isProxySetted()) { expectedException.expect(WifiProxyNotSettedException.class); } } }
It is commonly used in the Java virtual machine.
Oracle Java Turtorial
public class LibLoader { // , 2 . URLClassLoader urlClassLoader; String page; LibLoader(File myJar) throws MalformedURLException { urlClassLoader = new URLClassLoader(new URL[]{myJar.toURL()}, this.getClass().getClassLoader()); } public void loadPage(URL url) throws Exception { Class classToLoad = Class.forName("com.company.HtmlPageGetter", true, urlClassLoader); Method method = classToLoad.getDeclaredMethod("getPageFromURL", URL.class); Object instance = classToLoad.newInstance(); Object result = method.invoke(instance, url); page = (String) result; } public String getCurrentPage() { return page; } public void saveCurrentPage(String name) throws Exception { List<String> content = new ArrayList<>(); content.add(page); Class classToLoad = Class.forName("com.company.HtmlPageSaver", true, urlClassLoader); Method method = classToLoad.getDeclaredMethod("savePageToFile", String.class, List.class); Object instance = classToLoad.newInstance(); method.invoke(instance, name, content); } }
public static void main(String[] args) throws Exception { File lib = new File("htmlgetandsave.jar"); LibLoader libLoader = new LibLoader(lib); libLoader.loadPage(new URL("https://habrahabr.ru/post/69552/")); System.out.println(libLoader.getCurrentPage()); libLoader.saveCurrentPage(" - reflection "); }
public abstract class ReflectionHelper { /** * Used for getting public fields with @hide annotation */ public static Object getField(Object object, String name) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field field = object.getClass().getField(name); return field.get(object); } /** * Used for getting private fields */ public static Object getDeclaredField(Object object, String name) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field declaredField = object.getClass().getDeclaredField(name); declaredField.setAccessible(true); return declaredField.get(object); } /** * Used for setting private fields */ public static void setDeclaredField(Object object, String name, Object value) throws NoSuchFieldException, IllegalAccessException { Field declaredField = object.getClass().getDeclaredField(name); declaredField.setAccessible(true); declaredField.set(object, value); } /** * Used for setting Enum fields */ public static void setEnumField(Object object, String value, String name) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field field = object.getClass().getField(name); field.set(object, Enum.valueOf((Class<Enum>) field.getType(), value)); } /** * Used for simplifying process of invoking private method * Automatically detects args types and founds method to get and invoke */ public static Object getMethodAndInvokeIt(Object object, String methodName, Object... args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method method = object.getClass().getDeclaredMethod(methodName, parameterTypes(args)); method.setAccessible(true); return method.invoke(object, args); } private static Class[] parameterTypes(Object... args) { ArrayList<Class> classes = new ArrayList<>(); for (Object arg : args) { classes.add(arg.getClass()); } return classes.toArray(new Class[args.length]); } }
public class ApiNotSupportedException extends Exception { public ApiNotSupportedException() { super("Api version not supported"); } }
public class NullWifiConfigurationException extends Exception { public NullWifiConfigurationException(){ super("WiFi configuration was null. \n" + "If you are trying to change current network settings - check your connection."); } }
public class WifiProxyNotSettedException extends IllegalStateException{ public WifiProxyNotSettedException(){ super("Wifi proxy not setted for current WifiConfiguration"); } }
public class BaseWifiConfiguration { protected WifiConfiguration wifiConfiguration; protected BaseWifiConfiguration(WifiConfiguration wifiConfiguration) throws NullWifiConfigurationException { if (wifiConfiguration == null) throw new NullWifiConfigurationException(); this.wifiConfiguration = wifiConfiguration; } protected BaseWifiConfiguration(Context context) throws NullWifiConfigurationException { this(getCurrentWifiConfigurationFromContext(context)); } public WifiConfiguration getWifiConfiguration() { return wifiConfiguration; } private static WifiConfiguration getCurrentWifiConfigurationFromContext(Context context) { final WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); List<WifiConfiguration> wifiConfigurationList = manager.getConfiguredNetworks(); if (!manager.isWifiEnabled() || wifiConfigurationList == null || wifiConfigurationList.isEmpty()) return null; return findWifiConfigurationByNetworkId(wifiConfigurationList, manager.getConnectionInfo().getNetworkId()); } private static WifiConfiguration findWifiConfigurationByNetworkId(List<WifiConfiguration> wifiConfigurationList, int networkId) { for (WifiConfiguration wifiConf : wifiConfigurationList) { if (wifiConf.networkId == networkId) return wifiConf; } return null; } }
public interface ProxyChanger { void setProxySettings(ProxySettings proxySettings) throws NoSuchFieldException, IllegalAccessException; ProxySettings getProxySettings() throws NoSuchFieldException, IllegalAccessException; void setProxyHostAndPort(String host, int port) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException; String getProxyHost() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ApiNotSupportedException, NoSuchFieldException; int getProxyPort() throws ApiNotSupportedException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, NoSuchFieldException; boolean isProxySetted() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ApiNotSupportedException, NoSuchFieldException; WifiConfiguration getWifiConfiguration(); }
public enum ProxySettings { /* No proxy is to be used. Any existing proxy settings * should be cleared. */ NONE("NONE"), /* Use statically configured proxy. Configuration can be accessed * with httpProxy. */ STATIC("STATIC"), /* no proxy details are assigned, this is used to indicate * that any existing proxy settings should be retained */ UNASSIGNED("UNASSIGNED"), /* Use a Pac based proxy. */ PAC("PAC"); String value = ""; ProxySettings(String value) { this.value = value; } public String getValue() { return value; } }
public abstract class ProxyPropertiesConstructor { public static Object proxyProperties(String host, int port) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { return proxyProperties(host, port, null); } public static Object proxyProperties(String host, int port, String exclList) throws NoSuchMethodException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException { return proxyPropertiesConstructor().newInstance(host, port, exclList); } private static Constructor proxyPropertiesConstructor() throws ClassNotFoundException, NoSuchMethodException { return Class.forName("android.net.ProxyProperties").getConstructor(String.class, int.class, String.class); } }
public class ProxyPropertiesContainer { Object proxyProperties; ProxyPropertiesContainer(Object proxyProperties) { this.proxyProperties = proxyProperties; } ProxyPropertiesContainer(String host, int port) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { this(host, port, null); } ProxyPropertiesContainer(String host, int port, String exclList) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { this(ProxyPropertiesConstructor.proxyProperties(host, port, exclList)); } public String getHost() throws NoSuchFieldException, IllegalAccessException { return (String) ReflectionHelper.getDeclaredField(proxyProperties, "mHost"); } public int getPort() throws NoSuchFieldException, IllegalAccessException { return (int) ReflectionHelper.getDeclaredField(proxyProperties, "mPort"); } public String getExclusionList() throws NoSuchFieldException, IllegalAccessException { return (String) ReflectionHelper.getDeclaredField(proxyProperties, "mExclusionList"); } public Object getProxyProperties() { return proxyProperties; } }
public class WifiConfigurationForApiFrom15To19 extends BaseWifiConfiguration implements ProxyChanger { private ProxyPropertiesContainer proxyPropertiesContainer; public WifiConfigurationForApiFrom15To19(Context context) throws NoSuchFieldException, IllegalAccessException, NullWifiConfigurationException { super(context); this.proxyPropertiesContainer = new ProxyPropertiesContainer(getCurrentProxyProperties()); } public static WifiConfigurationForApiFrom15To19 createFromCurrentContext(Context context) throws NoSuchFieldException, IllegalAccessException, NullWifiConfigurationException { return new WifiConfigurationForApiFrom15To19(context); } @Override public void setProxySettings(ProxySettings proxySettings) throws NoSuchFieldException, IllegalAccessException { ReflectionHelper.setEnumField(wifiConfiguration, proxySettings.getValue(), "proxySettings"); } @Override public ProxySettings getProxySettings() throws NoSuchFieldException, IllegalAccessException { return ProxySettings.valueOf(String.valueOf(ReflectionHelper.getDeclaredField(wifiConfiguration, "proxySettings"))); } @Override public void setProxyHostAndPort(String host, int port) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException { proxyPropertiesContainer = new ProxyPropertiesContainer(host, port); ReflectionHelper.getMethodAndInvokeIt( getLinkProperties(), "setHttpProxy", proxyPropertiesContainer.getProxyProperties()); } @Override public String getProxyHost() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ApiNotSupportedException, NoSuchFieldException { if (proxyPropertiesContainer == null) throw new WifiProxyNotSettedException(); return proxyPropertiesContainer.getHost(); } @Override public int getProxyPort() throws ApiNotSupportedException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, NoSuchFieldException { if (proxyPropertiesContainer == null) throw new WifiProxyNotSettedException(); return proxyPropertiesContainer.getPort(); } @Override public boolean isProxySetted() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ApiNotSupportedException, NoSuchFieldException { return !(proxyPropertiesContainer == null); } private LinkProperties getLinkProperties() throws NoSuchFieldException, IllegalAccessException { return (LinkProperties) ReflectionHelper.getField(wifiConfiguration, "linkProperties"); } private Object getCurrentProxyProperties() throws NoSuchFieldException, IllegalAccessException { return ReflectionHelper.getDeclaredField(getLinkProperties(), "mHttpProxy"); } }
public abstract class ProxyInfoConstructor { public static ProxyInfo proxyInfo(String host, int port) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { return proxyInfo(host, port, null); } public static ProxyInfo proxyInfo(String host, int port, String exclude) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Object newProxyInfo = proxyInfoConstructor().newInstance(host, port, exclude); return (ProxyInfo) newProxyInfo; } private static Constructor proxyInfoConstructor() throws ClassNotFoundException, NoSuchMethodException { return Class.forName("android.net.ProxyInfo").getConstructor(String.class, int.class, String.class); } }
public class WifiConfigurationForApiFrom21To22 extends BaseWifiConfiguration implements ProxyChanger { public WifiConfigurationForApiFrom21To22(Context context) throws NullWifiConfigurationException { super(context); } public static WifiConfigurationForApiFrom21To22 createFromCurrentContext(Context context) throws NullWifiConfigurationException { return new WifiConfigurationForApiFrom21To22(context); } @Override public ProxySettings getProxySettings() throws NoSuchFieldException, IllegalAccessException { return ProxySettings.valueOf(String.valueOf(ReflectionHelper.getDeclaredField(getIpConfigurationObject(), "proxySettings"))); } @Override public void setProxySettings(ProxySettings proxySettings) throws NoSuchFieldException, IllegalAccessException { ReflectionHelper.setEnumField(getIpConfigurationObject(), proxySettings.getValue(), "proxySettings"); } @Override public void setProxyHostAndPort(String host, int port) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException { setProxyInfo(ProxyInfoConstructor.proxyInfo(host, port)); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public String getProxyHost() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ApiNotSupportedException { ProxyInfo info = getProxyInfo(); if (info == null) throw new WifiProxyNotSettedException(); return info.getHost(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public int getProxyPort() throws ApiNotSupportedException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { ProxyInfo info = getProxyInfo(); if (info == null) throw new WifiProxyNotSettedException(); return info.getPort(); } @Override public boolean isProxySetted() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ApiNotSupportedException, NoSuchFieldException { return !(getProxyInfo() == null); } private Object getIpConfigurationObject() throws NoSuchFieldException, IllegalAccessException { return ReflectionHelper.getDeclaredField(wifiConfiguration, "mIpConfiguration"); } private ProxyInfo getProxyInfo() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { return (ProxyInfo) ReflectionHelper.getMethodAndInvokeIt(wifiConfiguration, "getHttpProxy"); } private void setProxyInfo(ProxyInfo proxyInfo) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { ReflectionHelper.getMethodAndInvokeIt(wifiConfiguration, "setHttpProxy", proxyInfo); } }
public abstract class CurrentProxyChangerGetter { public static ProxyChanger chooseProxyChangerForCurrentApi(Context context) throws ApiNotSupportedException, NoSuchFieldException, IllegalAccessException, NullWifiConfigurationException { if (ApiChecker.isJellyBeanOrKitkat()) { return WifiConfigurationForApiFrom15To19.createFromCurrentContext(context); } else if (ApiChecker.isLolipop()) { return WifiConfigurationForApiFrom21To22.createFromCurrentContext(context); } else { throw new ApiNotSupportedException(); } } }
public abstract class WifiProxyChanger { public static void changeWifiStaticProxySettings(String host, int port, Context context) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException, ApiNotSupportedException, NullWifiConfigurationException { updateWifiWithNewConfiguration( getCurrentWifiConfiguretionWithUpdatedSettings(host, port, ProxySettings.STATIC, context), context); } public static void clearProxySettings(Context context) throws IllegalAccessException, ApiNotSupportedException, NoSuchFieldException, NullWifiConfigurationException, ClassNotFoundException, NoSuchMethodException, InstantiationException, InvocationTargetException { updateWifiWithNewConfiguration( getCurrentWifiConfiguretionWithUpdatedSettings("", 0, ProxySettings.NONE, context), context); } private static WifiConfiguration getCurrentWifiConfiguretionWithUpdatedSettings(String host, int port, ProxySettings proxySettings, Context context) throws ApiNotSupportedException, IllegalAccessException, NullWifiConfigurationException, NoSuchFieldException, ClassNotFoundException, NoSuchMethodException, InstantiationException, InvocationTargetException { ProxyChanger proxyChanger = CurrentProxyChangerGetter.chooseProxyChangerForCurrentApi(context); proxyChanger.setProxyHostAndPort(host, port); proxyChanger.setProxySettings(proxySettings); return proxyChanger.getWifiConfiguration(); } private static void updateWifiWithNewConfiguration(WifiConfiguration wifiConfiguration, Context context) { WifiManager currentWifiManager = NetworkHelper.getWifiManager(context); currentWifiManager.updateNetwork(wifiConfiguration); currentWifiManager.saveConfiguration(); currentWifiManager.reconnect(); } }
public abstract class WifiProxyInfo { public static String getHost(Context context) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ApiNotSupportedException, NoSuchFieldException, NullWifiConfigurationException { return CurrentProxyChangerGetter.chooseProxyChangerForCurrentApi(context).getProxyHost(); } public static int getPort(Context context) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ApiNotSupportedException, NoSuchFieldException, NullWifiConfigurationException { return CurrentProxyChangerGetter.chooseProxyChangerForCurrentApi(context).getProxyPort(); } public static ProxySettings getProxySettings(Context context) throws ApiNotSupportedException, IllegalAccessException, NoSuchFieldException, NullWifiConfigurationException { return CurrentProxyChangerGetter.chooseProxyChangerForCurrentApi(context).getProxySettings(); } }
public abstract class ApiChecker { public static boolean isJellyBeanOrKitkat() { return Build.VERSION.SDK_INT > 14 && Build.VERSION.SDK_INT < 20; } public static boolean isLolipop() { return Build.VERSION.SDK_INT > 20 && Build.VERSION.SDK_INT < 23; } public static boolean isSupportedApi() { return isJellyBeanOrKitkat() || isLolipop(); } }
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); changeProxySettings("myhost.com", 12345); } void changeProxySettings(String host, int port) { try { WifiProxyChanger.changeWifiStaticProxySettings(host, port, this); } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | InvocationTargetException | NoSuchFieldException | IllegalAccessException | NullWifiConfigurationException | ApiNotSupportedException e) { e.printStackTrace(); } } }
Source: https://habr.com/ru/post/311388/