很多时候,Java 应用程序需要连接到互联网。最常见的例子是在读取 XML 文件并需要下载其模式时。
我使用代理服务器。如何设置我的 JVM 使用代理?
我使用代理服务器。如何设置我的 JVM 使用代理?
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();
// proxy configuration read from file resource under "proxyFileName"
String proxyFileName = "proxy.txt"
String proxyPort = "1234"
String url = "http://www.promised.land"
File testProxyFile = new File(proxyFileName)
URLConnection connection
if (!testProxyFile.exists()) {
logger.debug "proxyFileName doesn't exist. Bypassing connection via proxy."
connection = url.toURL().openConnection()
} else {
String proxyAddress = testProxyFile.text
connection = url.toURL().openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort)))
}
try {
connection.connect()
}
catch (Exception e) {
logger.error e.printStackTrace()
}
完整参考文档:http://docs.oracle.com/javase/7/docs/technotes/guides/net/proxies.html
本文档介绍了Java中与代理服务器有关的内容,包括如何设置和使用代理服务器。如果您需要在网络通信过程中使用代理服务器,可以参考这份文档来了解相关知识。System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
System.getProperties().put("http.proxyUser", "someUserName");
System.getProperties().put("http.proxyPassword", "somePassword");
http.proxyUser
和 http.proxyPassword
不是Java系统属性,它们是用于Apache HTTP客户端的。 - user207421System.setProperty
替代 System.getProperties().put(...)
。 - Simon Forsberg最近我发现了一种让JVM使用浏览器代理设置的方法。你需要做的是将${java.home}/lib/deploy.jar
添加到你的项目中,并像下面这样初始化库:
import com.sun.deploy.net.proxy.DeployProxySelector;
import com.sun.deploy.services.PlatformType;
import com.sun.deploy.services.ServiceManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public abstract class ExtendedProxyManager {
private static final Log logger = LogFactory.getLog(ExtendedProxyManager.class);
/**
* After calling this method, proxy settings can be magically retrieved from default browser settings.
*/
public static boolean init() {
logger.debug("Init started");
// Initialization code was taken from com.sun.deploy.ClientContainer:
ServiceManager
.setService(System.getProperty("os.name").toLowerCase().indexOf("windows") != -1 ? PlatformType.STANDALONE_TIGER_WIN32
: PlatformType.STANDALONE_TIGER_UNIX);
try {
// This will call ProxySelector.setDefault():
DeployProxySelector.reset();
} catch (Throwable throwable) {
logger.error("Unable to initialize extended dynamic browser proxy settings support.", throwable);
return false;
}
return true;
}
}
接下来,代理设置可通过 java.net.ProxySelector
在 Java API 中使用。
这种方法的唯一问题是你需要在启动 JVM 时使用 deploy.jar
在 bootclasspath 中,例如 java -Xbootclasspath/a:"%JAVA_HOME%\jre\lib\deploy.jar" -jar my.jar
。如果有人知道如何克服这个限制,请告诉我。
xbootclasspath
指向deploy.jar
会产生什么影响,如果我在没有WebStart的情况下将该jar文件放到普通类路径上,会发生什么? - HoutmanException in thread "main" java.lang.IllegalAccessError: class ...) cannot access class com.sun.deploy.net.proxy.DeployProxySelector (in module jdk.deploy) because module jdk.deploy does not export com.sun.deploy.net.proxy
- Houtmanpublic 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");
}
}
附注:我基于GHad的答案。
正如其他答案所指出的那样,如果您需要使用身份验证代理,则没有可靠的方法仅使用命令行变量来实现这一点 - 如果您正在使用别人的应用程序并且不想干扰源代码,则这很烦人。
Will Iverson在使用HttpProxy连接到具有预先认证的主机上提出了有用的建议,建议使用代理管理工具,例如Proxifier( http://www.proxifier.com/适用于Mac OS X和Windows)来处理此问题。
例如,使用Proxifier,您可以设置它仅拦截要通过其(经过身份验证的)代理进行管理和重定向的Java命令。在这种情况下,您将希望将proxyHost和proxyPort值设置为空白,例如,将-Dhttp.proxyHost= -Dhttp.proxyPort=
传递给您的Java命令。
public static void main(String[] args) throws IOException {
System.setProperty("java.net.useSystemProxies", "true");
final String proxyUser = "proxy-user";
final String proxyPass = "password123";
final String host = "some.proxy.io";
final Integer port = 50201;
// http
System.setProperty("http.proxyHost",host);
System.setProperty("http.proxyPort", String.valueOf(port));
System.setProperty("http.proxyUser", proxyUser);
System.setProperty("http.proxyPassword", proxyPass);
// https
System.setProperty("https.proxyHost",host);
System.setProperty("https.proxyPort", String.valueOf(port));
System.setProperty("https.proxyUser", proxyUser);
System.setProperty("https.proxyPassword", proxyPass);
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
System.setProperty("jdk.https.auth.tunneling.disabledSchemes", "");
Authenticator.setDefault(new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(proxyUser, proxyPass.toCharArray());
}
}
);
// create and send a https request to myip.com API
URL url = new URL("https://api.myip.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int status = connection.getResponseCode();
// read the response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String responseLine;
StringBuffer responseContent = new StringBuffer();
while ((responseLine = in.readLine()) != null)
responseContent.append(responseLine);
in.close();
connection.disconnect();
// print the response
System.out.println(status);
System.out.println(responseContent);
}