Does Java's ProxySelector not work with automatic proxy configuration scripts?

前端 未结 5 2086
生来不讨喜
生来不讨喜 2020-12-01 03:14

I want my Java program to use the system\'s proxy configuration. Accordingly, I used the code found in many places, such as this answer, to set java.net.useSystemProxi

5条回答
  •  北海茫月
    2020-12-01 03:38

    As already suggested by Mads Hansen, Proxy-Vole does the trick!

    You just need to add the jar from the download site to your classpath (dlls are included) and this code helped me to configure the proxy stettings:

    ProxySearch proxySearch = new ProxySearch();
    proxySearch.addStrategy(Strategy.OS_DEFAULT); 
    proxySearch.addStrategy(Strategy.JAVA); 
    proxySearch.addStrategy(Strategy.BROWSER); 
    ProxySelector proxySelector = proxySearch.getProxySelector(); 
    
    ProxySelector.setDefault(proxySelector); 
    URI home = URI.create("http://www.google.com"); 
    System.out.println("ProxySelector: " + proxySelector); 
    System.out.println("URI: " + home); 
    List proxyList = proxySelector.select(home); 
    if (proxyList != null && !proxyList.isEmpty()) { 
     for (Proxy proxy : proxyList) { 
       System.out.println(proxy); 
       SocketAddress address = proxy.address(); 
       if (address instanceof InetSocketAddress) { 
         String host = ((InetSocketAddress) address).getHostName(); 
         String port = Integer.toString(((InetSocketAddress) address).getPort()); 
         System.setProperty("http.proxyHost", host); 
         System.setProperty("http.proxyPort", port); 
       } 
     } 
    }
    

提交回复
热议问题