在Java中配置代理服务器可以通过两种主要方法实现:通过系统属性设置和使用第三方库。以下是详细的步骤和示例:
全局代理设置: 在启动Java应用时,可以通过命令行参数设置系统属性,这些属性包括:
http.proxyHost
:HTTP代理服务器地址http.proxyPort
:HTTP代理服务器端口https.proxyHost
:HTTPS代理服务器地址https.proxyPort
:HTTPS代理服务器端口示例:
java -Dhttp.proxyHost=proxy.example.com -Dhttp.proxyPort=8080 -Dhttps.proxyHost=proxy.example.com -Dhttps.proxyPort=8080 MyApplication
或者在代码中设置这些系统属性:
System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");
System.setProperty("https.proxyHost", "proxy.example.com");
System.setProperty("https.proxyPort", "8080");
需要身份验证的代理:
如果代理服务器需要身份验证,可以设置http.proxyUser
和http.proxyPassword
属性:
System.setProperty("http.proxyUser", "username");
System.setProperty("http.proxyPassword", "password");
忽略某些URL:
使用http.nonProxyHosts
属性指定不需要通过代理的URL:
System.setProperty("http.nonProxyHosts", "localhost|*.mydomain.com");
Apache HttpClient:
在代码中创建一个HttpHost
对象并传递给HttpClientBuilder
:
CloseableHttpClient httpClient = HttpClients.custom()
.setProxy(new HttpHost("proxy.example.com", 8080, "http"))
.build();
OkHttp:
使用Proxy
类设置代理:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));
OkHttpClient client = new OkHttpClient.Builder().proxy(proxy).build();
Request request = new Request.Builder().url("http://www.example.com").build();
Response response = client.newCall(request).execute();
Forest: 使用注解来配置代理:
@HTTPProxy(host = "127.0.0.1", port = 1081, username = "root", password = "123456")
public interface MyClient {
@Get("https://example.com")
String getData();
}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。