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

前端 未结 19 1954
孤街浪徒
孤街浪徒 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:25

    To set an HTTP/HTTPS and/or SOCKS proxy programmatically:

    ...
    
    public void setProxy() {
        if (isUseHTTPProxy()) {
            // HTTP/HTTPS Proxy
            System.setProperty("http.proxyHost", getHTTPHost());
            System.setProperty("http.proxyPort", getHTTPPort());
            System.setProperty("https.proxyHost", getHTTPHost());
            System.setProperty("https.proxyPort", getHTTPPort());
            if (isUseHTTPAuth()) {
                String encoded = new String(Base64.encodeBase64((getHTTPUsername() + ":" + getHTTPPassword()).getBytes()));
                con.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
                Authenticator.setDefault(new ProxyAuth(getHTTPUsername(), getHTTPPassword()));
            }
        }
        if (isUseSOCKSProxy()) {
            // SOCKS Proxy
            System.setProperty("socksProxyHost", getSOCKSHost());
            System.setProperty("socksProxyPort", getSOCKSPort());
            if (isUseSOCKSAuth()) {
                System.setProperty("java.net.socks.username", getSOCKSUsername());
                System.setProperty("java.net.socks.password", getSOCKSPassword());
                Authenticator.setDefault(new ProxyAuth(getSOCKSUsername(), getSOCKSPassword()));
            }
        }
    }
    
    ...
    
    public class ProxyAuth extends Authenticator {
        private PasswordAuthentication auth;
    
        private ProxyAuth(String user, String password) {
            auth = new PasswordAuthentication(user, password == null ? new char[]{} : password.toCharArray());
        }
    
        protected PasswordAuthentication getPasswordAuthentication() {
            return auth;
        }
    }
    
    ...
    

    Remember that HTTP proxies and SOCKS proxies operate at different levels in the network stack, so you can use one or the other or both.

提交回复
热议问题