Java在Ubuntu上设置代理的方法
在启动Java应用程序时,直接通过-D参数传递代理配置,这是最灵活的方式,适用于单次运行或测试场景。
基础代理配置(覆盖HTTP/HTTPS协议):
java -Dhttp.proxyHost=proxy.example.com -Dhttp.proxyPort=8080 \
-Dhttps.proxyHost=proxy.example.com -Dhttps.proxyPort=8080 \
-jar your-application.jar
排除本地地址不走代理(避免循环代理):
java -Dhttp.proxyHost=proxy.example.com -Dhttp.proxyPort=8080 \
-Dhttps.proxyHost=proxy.example.com -Dhttps.proxyPort=8080 \
-Dhttp.nonProxyHosts="localhost|127.0.0.1|*.example.com" \
-jar your-application.jar
代理认证配置(若代理服务器需要用户名/密码):
java -Dhttp.proxyHost=proxy.example.com -Dhttp.proxyPort=8080 \
-Dhttps.proxyHost=proxy.example.com -Dhttps.proxyPort=8080 \
-Dhttp.proxyUser=username -Dhttp.proxyPassword=password \
-Dhttps.proxyUser=username -Dhttps.proxyPassword=password \
-jar your-application.jar
说明:http.nonProxyHosts支持通配符(如*.example.com表示该域名下的所有主机不走代理),多个地址用|分隔。
若希望当前终端会话中的所有Java应用都使用代理,可通过设置环境变量实现(仅对当前终端有效,关闭后失效)。
# 设置HTTP/HTTPS代理
export http_proxy=http://proxy.example.com:8080
export https_proxy=http://proxy.example.com:8080
# 排除本地地址(可选)
export no_proxy=localhost,127.0.0.1,*.example.com
# 启动Java应用(可结合JAVA_OPTS传递超时等参数)
java $JAVA_OPTS -jar your-application.jar
说明:no_proxy用于指定不走代理的地址,格式与http.nonProxyHosts一致。
若需要固定代理配置(不依赖外部参数),可在Java代码中通过System.setProperty设置代理属性。
public class Main {
public static void main(String[] args) {
// 设置代理主机和端口
System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");
System.setProperty("https.proxyHost", "proxy.example.com");
System.setProperty("https.proxyPort", "8080");
// 排除本地地址(可选)
System.setProperty("http.nonProxyHosts", "localhost|127.0.0.1|*.example.com");
// 测试网络连接(示例)
try {
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println("Connection successful!");
} catch (UnknownHostException e) {
System.err.println("Connection failed: " + e.getMessage());
}
}
}
注意:这种方式需修改代码并重新编译,适用于需要固定代理的场景。
若代理服务器需要身份验证,需补充proxyUser和proxyPassword参数:
System.setProperty("http.proxyUser", "your_username");
System.setProperty("http.proxyPassword", "your_password");
System.setProperty("https.proxyUser", "your_username");
System.setProperty("https.proxyPassword", "your_password");
安全提示:避免在代码中硬编码敏感信息(如密码),建议使用环境变量或配置文件管理。
编写简单的Java程序测试网络连接,确认代理配置是否正确:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ProxyTest {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println("Connected to: " + address.getHostAddress());
} catch (UnknownHostException e) {
System.err.println("Failed to connect. Check proxy settings.");
e.printStackTrace();
}
}
}
运行程序后,若能输出目标服务器的IP地址,则说明代理生效;若抛出UnknownHostException,需检查代理地址、端口或认证信息是否正确。