Java HTTP代理设置指南
在Java中设置HTTP代理可以通过多种方式实现,以下是几种常见的方法:

通过系统属性设置代理
这是最简单的方法,适用于整个JVM实例:
// 设置HTTP代理
System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");
// 设置HTTPS代理
System.setProperty("https.proxyHost", "proxy.example.com");
System.setProperty("https.proxyPort", "8080");
// 设置不使用代理的主机
System.setProperty("http.nonProxyHosts", "localhost|127.0.0.1|*.example.com");
通过代码为特定连接设置代理
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
public class ProxyExample {
public static void main(String[] args) throws Exception {
// 创建带有代理的HttpClient
HttpClient client = HttpClient.newBuilder()
.proxy(ProxySelector.of(new java.net.InetSocketAddress("proxy.example.com", 8080)))
.build();
// 创建HTTP请求
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com"))
.build();
// 发送请求并获取响应
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
为特定协议设置代理
// 仅为HTTP设置代理
ProxySelector httpProxy = ProxySelector.of(new java.net.InetSocketAddress("proxy.example.com", 8080));
HttpClient client = HttpClient.newBuilder()
.proxy(httpProxy)
.build();
使用认证的代理
如果代理需要用户名和密码:
import java.net.Authenticator;
import java.net.PasswordAuthentication;
// 设置代理认证
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType() == RequestorType.PROXY) {
return new PasswordAuthentication("username", "password".toCharArray());
}
return null;
}
});
// 然后设置代理主机和端口
System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");
对于旧版Java (Java 8及以下)
import java.net.URL;
import java.net.URLConnection;
URL url = new URL("http://example.com");
URLConnection conn = url.openConnection();
conn.setRequestProperty("Proxy-Authorization", "Basic " +
java.util.Base64.getEncoder().encodeToString("username:password".getBytes()));
禁用代理
// 禁用所有代理
System.setProperty("http.proxyHost", "");
System.setProperty("http.proxyPort", "");
System.setProperty("https.proxyHost", "");
System.setProperty("https.proxyPort", "");
// 或者使用ProxySelector
ProxySelector.setDefault(ProxySelector.of(null));
注意事项
- 代理设置对整个JVM有效,除非使用特定的HttpClient实例
- 对于需要NIO的HTTP客户端(如Java 11+的HttpClient),代理设置方式不同
- 考虑安全性,不要在代码中硬编码代理凭据
- 对于企业环境,通常需要设置
http.nonProxyHosts来排除内部服务器
选择哪种方法取决于你的具体需求和Java版本,现代Java应用推荐使用java.net.http.HttpClient(Java 11+)或Apache HttpClient等第三方库。

