简体   繁体   English

如何在Java中获得无代理连接?

[英]How to get a proxy-less connection in Java?

How do I avoid going through the ProxySelector when making a connection with URLConnection or rather how to get a connection guaranteed free of whatever proxies Java knows about ? 在与URLConnection建立连接时如何避免通过ProxySelector ,或者如何保证连接不受Java知道的任何代理的影响?

I thought this was what Proxy.NO_PROXY was for. 我认为这就是Proxy.NO_PROXY的用途。 Quoting from the Javadoc: 引用Javadoc:

A proxy setting that represents a DIRECT connection, basically telling the protocol handler not to use any proxying 代表DIRECT连接的代理设置,基本上告诉协议处理程序不使用任何代理

Yet such a connection will still go through the ProxySelector. 然而,这样的连接仍将通过ProxySelector。 I don't get it ?? 我不明白吗?

I've made a small test to prove my point: 我做了一个小测试来证明我的观点:

public static void main(String[] args) throws MalformedURLException, IOException {
    ProxySelector.setDefault(new MyProxySelector());
    URL url = new URL("http://foobar.com/x1/x2");
    URLConnection connection = url.openConnection(Proxy.NO_PROXY);
    connection.connect();
}

and a dummy ProxySelector which does nothing but log what is going on: 和一个虚拟的ProxySelector,除了记录正在发生的事情之外什么都不做:

public class MyProxySelector extends ProxySelector {

    @Override
    public List<Proxy> select(URI uri) {
        System.out.println("MyProxySelector called with URI = " + uri);
        return Collections.singletonList(Proxy.NO_PROXY);
    }

    @Override
    public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {}
}

which prints: 打印:

"MyProxySelector called with URI = socket://foobar.com:80"

(Note how the protocol has changed from http to socket ) (注意协议如何从http更改为socket

I can of course create my ProxySelector in such a way so that it always returns Proxy.NO_PROXY if the URI scheme is socket but I guess there would be occasions where there's a SOCKS proxy on the site and then it wouldn't be true. 我当然可以这样创建我的ProxySelector,以便它始终返回Proxy.NO_PROXY如果URI方案是socket但我想有可能在网站上有一个SOCKS代理然后它不会是真的。

Let me restate the question: I need a way to make sure a specific URLConnection doesn't use a proxy, regardless of what System Properties may be set or what ProxySelector is installed. 让我重申一下这个问题:我需要一种方法来确保特定的URLConnection不使用代理,无论可以设置什么系统属性或安装什么ProxySelector。

这被跟踪为JDK bug 8144008

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM