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

前端 未结 19 1597
孤街浪徒
孤街浪徒 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 06:24

    You can set some properties about the proxy server as jvm parameters

    -Dhttp.proxyPort=8080, proxyHost, etc.

    but if you need pass through an authenticating proxy, you need an authenticator like this example:

    ProxyAuthenticator.java

    import java.net.*;
    import java.io.*;
    
    public class ProxyAuthenticator extends Authenticator {
    
        private String userName, password;
    
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password.toCharArray());
        }
    
        public ProxyAuthenticator(String userName, String password) {
            this.userName = userName;
            this.password = password;
        }
    }
    

    Example.java

        import java.net.Authenticator;
        import ProxyAuthenticator;
    
    public class Example {
    
        public static void main(String[] args) {
            String username = System.getProperty("proxy.authentication.username");
            String password = System.getProperty("proxy.authentication.password");
    
                    if (username != null && !username.equals("")) {
                Authenticator.setDefault(new ProxyAuthenticator(username, password));
            }
    
                    // here your JVM will be authenticated
    
        }
    }
    

    Based on this reply: http://mail-archives.apache.org/mod_mbox/jakarta-jmeter-user/200208.mbox/%3C494FD350388AD511A9DD00025530F33102F1DC2C@MMSX006%3E

提交回复
热议问题