How to get a proxy-less connection in Java?

不问归期 提交于 2019-12-13 12:06:05

问题


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 ?

I thought this was what Proxy.NO_PROXY was for. Quoting from the Javadoc:

A proxy setting that represents a DIRECT connection, basically telling the protocol handler not to use any proxying

Yet such a connection will still go through the 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:

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)

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.

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.


回答1:


This is tracked as JDK bug 8144008.



来源:https://stackoverflow.com/questions/33575722/how-to-get-a-proxy-less-connection-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!