使用Java检测Windows/IE代理设置 [英] Detecting Windows/IE proxy setting using Java

查看:410
本文介绍了使用Java检测Windows/IE代理设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要自动检测用户是否需要代理才能访问互联网. Java应用程序是否可以读取系统代理设置?

I need to automatically detect if a user requires a proxy to access the internet. Is there a way for a Java application to read the systems proxy setting?

谢谢, 吉米

推荐答案

Java SE 1.5提供了ProxySelector类来检测代理设置.如果存在与Internet的直接连接,则代理类型将为DIRECT,否则它将返回主机和端口.

Java SE 1.5 provides ProxySelector class to detect the proxy settings. If there is a Direct connection to Internet the Proxy type will be DIRECT else it will return the host and port.

以下示例说明了此功能:

Example below illustrates this functionality:

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.util.Iterator;
import java.util.List;

public class TestProxy {

    public static void main(String[] args) {
        try {
            System.setProperty("java.net.useSystemProxies","true");
            List<Proxy> l = ProxySelector.getDefault().select(
                        new URI("http://www.yahoo.com/"));

            for (Iterator<Proxy> iter = l.iterator(); iter.hasNext(); ) {

                Proxy proxy = iter.next();

                System.out.println("proxy hostname : " + proxy.type());

                InetSocketAddress addr = (InetSocketAddress)proxy.address();

                if(addr == null) {

                    System.out.println("No Proxy");

                } else {
                    System.out.println("proxy hostname : " + addr.getHostName());
                    System.out.println("proxy port : " + addr.getPort());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这篇关于使用Java检测Windows/IE代理设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆