How do I set the proxy to be used by the JVM

前端 未结 19 1952
孤街浪徒
孤街浪徒 2020-11-22 05:51

Many times, a Java app needs to connect to the Internet. The most common example happens when it is reading an XML file and needs to download its schema.

I am behind

19条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 06:19

    This is a minor update, but since Java 7, proxy connections can now be created programmatically rather than through system properties. This may be useful if:

    1. Proxy needs to be dynamically rotated during the program's runtime
    2. Multiple parallel proxies need to be used
    3. Or just make your code cleaner :)

    Here's a contrived example in groovy:

    // proxy configuration read from file resource under "proxyFileName"
    String proxyFileName = "proxy.txt"
    String proxyPort = "1234"
    String url = "http://www.promised.land"
    File testProxyFile = new File(proxyFileName)
    URLConnection connection
    
    if (!testProxyFile.exists()) {
    
        logger.debug "proxyFileName doesn't exist.  Bypassing connection via proxy."
        connection = url.toURL().openConnection()
    
    } else {
        String proxyAddress = testProxyFile.text
        connection = url.toURL().openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort)))
    }
    
    try {
        connection.connect()
    }
    catch (Exception e) {
        logger.error e.printStackTrace()
    }
    

    Full Reference: http://docs.oracle.com/javase/7/docs/technotes/guides/net/proxies.html

提交回复
热议问题