9

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.

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.

YoYo
  • 9,157
  • 8
  • 57
  • 74
Theodor Keinstein
  • 1,653
  • 2
  • 26
  • 47
  • 1
    First check that windows really knows about your proxy: `netsh winhttp show proxy` (this lists the system wide proxies that java use in your example) – dacwe May 06 '11 at 11:02
  • It says `Following command was not found: winhttp` – Theodor Keinstein May 26 '11 at 05:04
  • How do you know that you are behind a proxy then? Is it a http proxy? Do you have it in your browser? – dacwe May 26 '11 at 07:01
  • Yes, I do. Browser (MSIE even Firefox) uses script for automatical setting. May it be the reason? MSIE is tight connected with Windows, but settings are most likely applied just for browser, not for entire environment. – Theodor Keinstein May 26 '11 at 08:54
  • Exaktly! It's just used for the browser. – dacwe May 26 '11 at 09:00

2 Answers2

6

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 this web page for details).

dacwe
  • 43,066
  • 12
  • 116
  • 140
  • Note that this applies only to applets as it executes in a container on your browser. It does not apply to stand-alone code like it is executed in the code example provided by the OP. – YoYo Jul 15 '15 at 19:06
2

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.

Theodor Keinstein
  • 1,653
  • 2
  • 26
  • 47
  • Your answer to your own question is actually the correct answer. Browser settings are not considered for your java code (as it is not an applet). It a maximum it will use the System default settings as set in the Internet Properties (LAN settings button) from your windows control panel (assuming you are using a windows host). See [another article](http://stackoverflow.com/a/31391184/744133) for more. – YoYo Jul 15 '15 at 19:31