Search code examples
javaurlconnectionproxy-server

How to get the name or ip of a proxy server in a managed network?


i need to be able to access certain urls programmatically . I am using URLConnection as follows

URL url = new URL(http,         
                  myProxy.com, // I need to know this parameter   
                  -1,              
                  http://www.example.com/);    

How do I get the name of the proxy server used in a managed network.

when i use a browser like chrome it connects me with the proxy server that makes requests to the internet . How do i get the name of the proxy server ?


Solution

  • You can try to use a java ProxySelector class to do it, her is short example of it'usage from java proxy configuration guide:

    private Proxy findProxy(URI uri)
    {
       try
       {
          ProxySelector selector = ProxySelector.getDefault();
          List<Proxy> proxyList = selector.select(uri);
          if (proxyList.size() > 1)
               return proxyList.get(0);
       }
       catch (IllegalArgumentException e)
       {
       }
       return Proxy.NO_PROXY;
    }
    

    To get a host name and IP address, you can use an InetSocketAddress, which you can get from Proxy instance:

    InetSocketAddress addr = (InetSocketAddress) proxy.address(); 
    if(addr != null) { 
      System.out.println("proxy hostname : " + addr.getHostName()); 
      System.out.println("proxy port : " + addr.getPort()); 
    } 
    

    But as I know, it's needed to set a system property to do it:

    System.setProperty("java.net.useSystemProxies","true");
    

    One more solution is to use a proxy-vole library to do it. Here is some usage examples.