很多时候,Java应用程序需要连接到Internet。最常见的例子发生在读取XML文件并需要下载其模式时。

我在代理服务器后面。如何将JVM设置为使用代理?


当前回答

将usesystemagents属性设置为true。例如,您可以通过JAVA_TOOL_OPTIONS环境变量来设置它。例如,在Ubuntu中,你可以在.bashrc中添加以下代码行:

export JAVA_TOOL_OPTIONS+=" - djava.net.usesystemagents =true"

其他回答

综合Sorter和javabrett/Leonel的回答:

java -Dhttp.proxyHost=10.10.10.10 -Dhttp.proxyPort=8080 -Dhttp.proxyUser=username -Dhttp.proxyPassword=password -jar myJar.jar

下面展示了如何在Java中通过命令行设置具有代理用户和代理密码的代理,这是一种非常常见的情况。首先,您不应该在代码中保存密码和主机,这是一个规则。

在命令行中使用-D传递系统属性,并使用system在代码中设置它们。setProperty("name", "value")是等价的。

但是请注意

工作的例子:

C:\temp>java -Dhttps.proxyHost=host -Dhttps.proxyPort=port -Dhttps.proxyUser=user -Dhttps.proxyPassword="password" -Djavax.net.ssl.trustStore=c:/cacerts -Djavax.net.ssl.trustStorePassword=changeit com.andreas.JavaNetHttpConnection

但是下面的方法不起作用:

C:\temp>java com.andreas.JavaNetHttpConnection -Dhttps.proxyHost=host -Dhttps.proxyPort=port -Dhttps=proxyUser=user -Dhttps.proxyPassword="password" -Djavax.net.ssl.trustStore=c:/cacerts -Djavax.net.ssl.trustStorePassword=changeit

唯一的区别是系统属性的位置!(上课前后)

如果你的密码中有特殊字符,你可以把它放在引号中“@MyPass123%”,就像上面的例子一样。

访问HTTPS服务时,必须使用HTTPS协议。proxyHost, https。proxyPort等等。

如果访问HTTP服务,必须使用HTTP。proxyHost, http。proxyPort等等。

这对我来说很管用:

public void setHttpProxy(boolean isNeedProxy) {
    if (isNeedProxy) {
        System.setProperty("http.proxyHost", getProxyHost());
        System.setProperty("http.proxyPort", getProxyPort());
    } else {
        System.clearProperty("http.proxyHost");
        System.clearProperty("http.proxyPort");
    }
}

P/S:我基于GHad的回答。

如果你想要“Socks Proxy”,通知“socksProxyHost”和“socksProxyPort”虚拟机参数。

e.g.

java -DsocksProxyHost=127.0.0.1 -DsocksProxyPort=8080 org.example.Main

我也在防火墙后面,这对我有用!!

System.setProperty("http.proxyHost", "proxy host addr");
System.setProperty("http.proxyPort", "808");
Authenticator.setDefault(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {

        return new PasswordAuthentication("domain\\user","password".toCharArray());
    }
});

URL url = new URL("http://www.google.com/");
URLConnection con = url.openConnection();

BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));

// Read it ...
String inputLine;
while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);

in.close();