Java中使用IE Proxy代理的方法

在Java的网络编程中,有时候内网服务器需要访问外网的网络资源,这时候就需要使用代理。

完整的代码下载:src.rar

一般系统在ie浏览器中设置的代理,java无法访问到,可通过以下代码进行:

    static {
   
        ProxySelector.setDefault(ProxyUtils.getProxySelectorOfIE());
    }

使用时,需要创建4个类,完整的代码如下:

package com.tool.utils;

import java.lang.reflect.Method;

/**
 *
 * @since 2016-05-17
 */
public final class StringUtils {
   

    private StringUtils() {
   }

    public static boolean isEmpty(String text) {
   
        return text == null || text.length() == 0;
    }

    public static boolean isNotEmpty(String text) {
   
        return !isEmpty(text);
    }

    public static String getGetterName(Method mtd) {
   
        String name = mtd.getName();
        if (name.startsWith("get")) {
   
            return Character.toLowerCase(name.charAt(3)) + name.substring(4);
        }
        if (name.startsWith("is")) {
   
            return Character.toLowerCase(name.charAt(2)) + name.substring(3);
        }
        return null;
    }

    public static String toGetterName(String name) {
   
        return "get" + Character.toUpperCase(name.charAt(0)) + name.substring(1);
    }

}

package com.tool.utils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;

/**
 * 获得系统的IE代理设置的工具类
 *
 * 用法是:
 * ProxySelector proxySelector = ProxyUtils.getProxySelectorOfIE();
 *
 * 只能在windows系统中执行
 *
 * @see ProxySelector
 */
public class ProxyUtils {
   

    private static final String PATH_IE_SETTING = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
    private static final String BOOL_STR = "0x1";
    private static final String KEY_PROXY_SERVER = "ProxyServer";
    private static final String KEY_PROXY_ENABLE = "ProxyEnable";
    private static final String KEY_PROXY_OVERRIDE = "ProxyOverride";


    /**
     * 获得ie浏览器的代理,如果在linux环境下执行,会抛出异常
     *
     * @return ie浏览器设置的默认代理,如果没开启则返回null
     */
    public static Proxy getProxyOfIE() {
   
        checkWindows();
        try {
   
            if (isProxyEnable()) {
   
                String server = WinRegistry.valueForKey(WinRegistry.HKEY_CURRENT_USER, PATH_IE_SETTING, KEY_PROXY_SERVER);
                if (StringUtils.isNotEmpty(server)) {
   
                    int i = server.indexOf(":");
                    String host = server.substring(0, i);
                    int port = Integer.parseInt(server.substring(i + 1));
                    return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
                }
            }
            return null;
        } catch (Exception e) {
   
            throw new RuntimeException("failed to read the settings of the ie.", e);
        }
    }

    /**
     * 获得ie浏览器的ProxySelector,如果在linux环境下执行,会抛出异常
     *
     * @see ProxySelector
     * @return ie浏览器设置的默认ProxySelector,如果没开启则返回{@code ProxySelector.getDefault()}
     */
    public static ProxySelector getProxySelectorOfIE() {
   
        checkWindows();
        try{
   
            Proxy proxy = getProxyOfIE();
            String proxyOverride = WinRegistry.valueForKey(WinRegistry.HKEY_CURRENT_USER,PATH_IE_SETTING,KEY_PROXY_OVERRIDE);
            if(StringUtils.isEmpty(proxyOverride)){
   
                return new AddressProxySelector(proxy);
            }
            return new AddressProxySelector(proxyOverride,proxy);
        } catch (Exception e) {
   
            throw new RuntimeException("failed to read the settings of the ie.", e);
        }
    }


    private static boolean isProxyEnable() throws IllegalAccessException, IOException, InvocationTargetException {
   
        String proxyEnable = WinRegistry.valueForKey(
                WinRegistry.HKEY_CURRENT_USER,
                PATH_IE_SETTING,
                KEY_PROXY_ENABLE
        );
        return BOOL_STR.equalsIgnoreCase(proxyEnable);
    }

    private static void checkWindows() {
   
        String os = System.getProperty("os.name");
        if (!os.toLowerCase().startsWith("win")) {
   
            throw new IllegalStateException("this method can only run in windows os!");
        }
    }
}

package com.tool.utils;

import java.io.IOException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class AddressProxySelector extends ProxySelector {
   

    private String[] hosts;
    private Proxy proxy;


    public AddressProxySelector(Proxy proxy) {
   
        if (proxy == null) {
   
            proxy = Proxy.NO_PROXY;
        }
        this.proxy = proxy;
    }

    public AddressProxySelector(String host, Proxy proxy) {
   
        if (proxy == null) {
   
            proxy = Proxy.NO_PROXY;
        }
        this.hosts = host.split(";");
        this.proxy = proxy;
    }

    @Override
    public List<Proxy> select(URI uri) {
   
        if (uri == null) {
   
            throw new IllegalArgumentException("URI can't be null.");
        }
        if (hosts == null) {
   
            return Collections.singletonList(this.proxy);
        }
        String uriHost = uri.getHost();
        if (Arrays.stream(hosts).anyMatch(host -> matches(host, uriHost))) {
   
            return Collections.singletonList(Proxy.NO_PROXY);
        }
        return Collections.singletonList(this.proxy);
    }

    private static boolean matches(String exp, String str) {
   
        if ("<local>".equals(exp)) {
   
            //匹配localhost
            return "localhost".equalsIgnoreCase(str) || "127.0.0.1".equals(str)<
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值