JAVA通过注册表获取Internet代理设置



描述:这里利用JNI方式(涉及到本地动态链接库ICE_JNIRegistry.dll和注册表操作类库registry.jar)。首先Registry.openSubkey()打开指定的注册表项,然后获取其下的键ProxyEnable的值。若ProxyEnable值为0,则代理未开启;若ProxyEnable值不为0,则表明代理开启,获取键ProxyServer的值,并据此设置代理服务器的各个协议。


说明1 键ProxyEnable的值是16进制,双字节DWORD的,用来表明系统当前是否开启Internet代理。

说明2 键ProxyServer的值是一字符串,用来指明系统当前的Internet代理服务器设置。这一设置分为二种情况,其一是对所有协议使用统一的代理服务器设置(值如:172.23.196.238:808),其二是所有协议使用自定义的代理服务器设置(值如:ftp=172.23.196.221:808;gopher=172.23.196.221:808;http=172.23.196.221:808;https=172.23.196.221:808;socks=172.23.196.221:1080)。


Java代码 复制代码 收藏代码spinner.gif
  1. /**

  2. * Copyright (c) 2012 Trusted Software and Mobile Computing(TSMC)

  3. * All right reserved.

  4. *

  5. * Created on Apr 24, 2012 12:42:24 PM

  6. * http://jarg.iteye.com/

  7. * Author: Jarg Yee <yeshaoting@gmail.com>

  8. */

  9. package com.iteye.jarg.monitor.util;  


  10. import java.io.BufferedInputStream;  

  11. import java.io.IOException;  

  12. import java.io.InputStream;  

  13. import java.net.URL;  

  14. import java.net.URLConnection;  

  15. import java.util.Properties;  


  16. import com.ice.jni.registry.RegDWordValue;  

  17. import com.ice.jni.registry.Registry;  

  18. import com.ice.jni.registry.RegistryKey;  

  19. import com.ice.jni.registry.RegistryValue;  


  20. /**

  21. * TODO 使用Internet代理服务器工具类

  22. * 2012-04-25 11:49

  23. */

  24. publicclass InternetUtil  

  25. {  


  26. /** 获取系统配置句柄 */

  27. privatestaticfinal Properties prop = System.getProperties();  


  28. /** 注册表中Internet表项位置 */

  29. privatestaticfinal String Internet = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";  



  30. /** 初始化代理 from Internet Settings */

  31. publicstaticvoid initProxy()  

  32.    {  


  33. try

  34.        {  

  35. // 注册表表项值

  36.            RegistryKey registryKey = Registry.openSubkey(Registry.HKEY_CURRENT_USER, Internet, RegistryKey.ACCESS_READ);  


  37. // 注册表表项键

  38.            RegistryValue registryValue = registryKey.getValue("ProxyEnable");  

  39. boolean proxyEnable = ((RegDWordValue) registryValue).getData() != 0;   // 代理设置是否开启

  40. //          System.out.println("IE 是否启用了代理设置: " + proxyEnable);


  41. if (proxyEnable == true)    // 开启了Internet代理

  42.            {  

  43.                registryValue = registryKey.getValue("ProxyServer");  

  44.                String proxyServer = new String(registryValue.getByteData());  

  45.                ProxyUtil.initProxy(proxyServer);  

  46.                System.out.println("使用IE代理服务器.");  

  47.            }  

  48.        }  

  49. catch (Exception e)  

  50.        {  

  51.            System.out.println("ERROR:操作Windows注册表失败.");  

  52. //          e.printStackTrace();

  53.        }  

  54.    }  


  55. }