如何从 Java 中的系统设置中获取代理设置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5910001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:23:56  来源:igfitidea点击:

How to get proxy settings from system settings in Java

javanetworkingproxy

提问by Theodor Keinstein

I'm looking form way how to get system proxy information in Java under Windows, but I've found just one way. But it does not work for me.

我正在寻找如何在 Windows 下用 Java 获取系统代理信息的方式,但我只找到了一种方法。但它对我不起作用。

public static void main(String[] args) throws Throwable {
  System.setProperty("java.net.useSystemProxies", "true");
  System.out.println("detecting proxies");
  List<Proxy> pl = ProxySelector.getDefault().select(new URI("http://ihned.cz/"));
  for (Proxy p : pl)
    System.out.println(p);
  Proxy p = null;
  if (pl.size() > 0) //uses first one
    p = pl.get(0);
  System.out.println(p.address());
  System.out.println("Done");
}

When I run the program, I get:

当我运行程序时,我得到:

detecting proxies
DIRECT
null
Done

Java means, that I'm situated directly on internet. But it's wrong. I'm behind proxy. I'm unable to get the solution for my computer.

Java 的意思是,我直接位于互联网上。但这是错误的。我在代理后面。我无法获得适用于我的计算机的解决方案。

采纳答案by dacwe

As we discussed in the comments the proxy settings is just applied for some of browsers you use.

正如我们在评论中所讨论的,代理设置仅适用于您使用的某些浏览器。

If you want Java to use the same settings you need to manually put it into the java network settings (check thisweb page for details).

如果您希望 Java 使用相同的设置,您需要手动将其放入 Java 网络设置(查看网页了解详细信息)。

回答by Theodor Keinstein

Thanks to Dacwe. The problem is, that browser does not use any system proxy, but it sets proxy self using a script. Thus there are not any proxies in the system and Java cannot reach them.

感谢达威。问题是,该浏览器不使用任何系统代理,而是使用脚本设置代理自身。因此,系统中没有任何代理,Java 无法访问它们。