Setting JVM/JRE to use Windows Proxy Automatically

前端 未结 6 1348
[愿得一人]
[愿得一人] 2020-11-28 06:29

I did see the question about setting the proxy for the JVM but what I want to ask is how one can utilize the proxy that is already configured (on Windows).

Here is a

6条回答
  •  清酒与你
    2020-11-28 06:35

    It is possible to detect the proxy using the ProxySelector class and assign the system proxy by assigning environment variables with the setProperty method of the System class:

    System.setProperty("java.net.useSystemProxies", "true");
    System.out.println("detecting proxies");
    List l = null;
    try {
        l = ProxySelector.getDefault().select(new URI("http://foo/bar"));
    } 
    catch (URISyntaxException e) {
        e.printStackTrace();
    }
    if (l != null) {
        for (Iterator iter = l.iterator(); iter.hasNext();) {
            java.net.Proxy proxy = (java.net.Proxy) iter.next();
            System.out.println("proxy type: " + proxy.type());
    
            InetSocketAddress addr = (InetSocketAddress) proxy.address();
    
            if (addr == null) {
                System.out.println("No Proxy");
            } else {
                System.out.println("proxy hostname: " + addr.getHostName());
                System.setProperty("http.proxyHost", addr.getHostName());
                System.out.println("proxy port: " + addr.getPort());
                System.setProperty("http.proxyPort", Integer.toString(addr.getPort()));
            }
        }
    }
    

提交回复
热议问题