8 months ago I used this stack overflow post to automatically use a proxy server in a Java project. It worked beautifully.
Here is the code I came up with at the time:
System.setProperty("java.net.useSystemProxies", "true");
List<Proxy> proxyServers = null;
try {
proxyServers = ProxySelector.getDefault().select(new URI("http://www.twitter.com"));
} catch (URISyntaxException e) {
System.out.println("Error using system proxy");
}
if (proxyServers != null) {
for (Iterator<Proxy> iter = proxyServers.iterator(); iter.hasNext();) {
Proxy proxy = iter.next();
System.out.println("Found Proxy: " + proxy);
InetSocketAddress addr = (InetSocketAddress) proxy.address();
if (addr == null) {
System.out.println("No Proxy");
} else {
System.setProperty("http.proxyHost", addr.getHostName());
System.setProperty("http.proxyPort", Integer.toString(addr.getPort()));
System.out.println("proxy hostname : " + addr.getHostName());
System.out.println("proxy port : " + addr.getPort());
}
}
}
I tried adding this exact same code to another project recently and I get different results. I have my computer setup to use a test proxy server and ran both projects to compare the results. If I run the project from 8 months ago the following is printed out:
Found Proxy: HTTP @ 192.168.1.100:8000
proxy hostname : 192.168.1.100
proxy port : 8000
If I run my current project on the same machine with the same Proxy server set up, the following is printed out.
Found Proxy: DIRECT
No Proxy
The only proxy found is a "Direct" and proxy.address() is null.
What would cause this to find the proxy settings in one case but not the other?
Edit:
I fixed this, by moving the code sooner in the startup process, but I don't know why this fixed it.