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

编程入门 行业动态 更新时间:2024-10-13 12:24:42
本文介绍了如何在Java中获得无代理连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在与 URLConnection 建立连接时,如何避免通过 ProxySelector ,或者更确切地说如何获取连接保证没有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 ?

我认为这是 Proxy.NO_PROXY 用于。引自Javadoc:

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

代表DIRECT连接的代理设置,基本上告诉协议处理程序不使用任何代理

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

然而,这样的连接仍将通过ProxySelector。我不明白吗?

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("foobar/x1/x2"); URLConnection connection = url.openConnection(Proxy.NO_PROXY); connection.connect(); }

和一个虚拟的ProxySelector,除了记录正在发生的事情之外什么都不做:

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) {} }

打印:

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

(注意如何协议已从 http 更改为套接字)

(Note how the protocol has changed from http to socket)

我当然可以这样创建我的ProxySelector,以便它总是返回 Proxy.NO_PROXY 如果URI方案是 socket 但我想有可能在网站上有一个SOCKS代理,然后它就不会是真的。

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.

让我重申一个问题:我需要一个方法确保特定的 URLConnection 不使用代理,无论可以设置什么系统属性或安装什么ProxySelector。

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.

推荐答案

这被跟踪为 JDK bug 8144008 。

更多推荐

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

本文发布于:2023-11-25 20:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631261.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!