如何设置JVM使用的代理

时间:2023-01-02 18:05:30

Many times, a Java app needs to connect to the Internet. The most common example happens when it is reading an XML file and needs to download its schema.

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

I am behind a proxy server. How do I set my JVM to use the proxy ?

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

20 个解决方案

#1


290  

From the Java documentation (not the javadoc API):

从Java文档(而不是javadoc API):

http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html

http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html

Set the JVM flags http.proxyHost and http.proxyPort when starting your JVM on the command line. This is usually done in a shell script (in Unix) or bat file (in Windows). Here's the example with the Unix shell script:

设置JVM标记http。proxyHost和http。在命令行上启动JVM时使用proxyPort。这通常是在shell脚本(在Unix中)或bat文件(在Windows中)完成的。下面是Unix shell脚本的示例:

JAVA_FLAGS=-Dhttp.proxyHost=10.0.0.100 -Dhttp.proxyPort=8800
java ${JAVA_FLAGS} ...

When using containers such as JBoss or WebLogic, my solution is to edit the start-up scripts supplied by the vendor.

当使用JBoss或WebLogic等容器时,我的解决方案是编辑供应商提供的启动脚本。

Many developers are familiar with the Java API (javadocs), but many times the rest of the documentation is overlooked. It contains a lot of interesting information: http://download.oracle.com/javase/6/docs/technotes/guides/

许多开发人员都熟悉Java API (javadocs),但是很多时候文档的其余部分都被忽略了。它包含了很多有趣的信息:http://download.oracle.com/javase/6/docs/technotes/guides/


Update : If you do not want to use proxy to resolve some local/intranet hosts, check out the comment from @Tomalak:

更新:如果您不想使用代理解析某些本地/内部网主机,请查看@Tomalak的评论:

Also don't forget the http.nonProxyHosts property!

也不要忘记http。nonProxyHosts财产!

-Dhttp.nonProxyHosts="localhost|127.0.0.1|10.*.*.*|*.foo.com‌​|etc"

#2


73  

To set an HTTP/HTTPS and/or SOCKS proxy programmatically:

以编程方式设置HTTP/HTTPS和/或SOCKS代理:

...

public void setProxy() {
    if (isUseHTTPProxy()) {
        // HTTP/HTTPS Proxy
        System.setProperty("http.proxyHost", getHTTPHost());
        System.setProperty("http.proxyPort", getHTTPPort());
        System.setProperty("https.proxyHost", getHTTPHost());
        System.setProperty("https.proxyPort", getHTTPPort());
        if (isUseHTTPAuth()) {
            String encoded = new String(Base64.encodeBase64((getHTTPUsername() + ":" + getHTTPPassword()).getBytes()));
            con.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
            Authenticator.setDefault(new ProxyAuth(getHTTPUsername(), getHTTPPassword()));
        }
    }
    if (isUseSOCKSProxy()) {
        // SOCKS Proxy
        System.setProperty("socksProxyHost", getSOCKSHost());
        System.setProperty("socksProxyPort", getSOCKSPort());
        if (isUseSOCKSAuth()) {
            System.setProperty("java.net.socks.username", getSOCKSUsername());
            System.setProperty("java.net.socks.password", getSOCKSPassword());
            Authenticator.setDefault(new ProxyAuth(getSOCKSUsername(), getSOCKSPassword()));
        }
    }
}

...

public class ProxyAuth extends Authenticator {
    private PasswordAuthentication auth;

    private ProxyAuth(String user, String password) {
        auth = new PasswordAuthentication(user, password == null ? new char[]{} : password.toCharArray());
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return auth;
    }
}

...

Remember that HTTP proxies and SOCKS proxies operate at different levels in the network stack, so you can use one or the other or both.

请记住,HTTP代理和SOCKS代理在网络堆栈中的不同级别上操作,因此您可以使用一个或另一个或两个。

#3


72  

To use the system proxy setup:

使用系统代理设置:

java -Djava.net.useSystemProxies=true ...

Or programatically:

或编程:

System.setProperty("java.net.useSystemProxies", "true");

Source: http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html

来源:http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html

#4


37  

You can set those flags programmatically this way:

您可以通过编程方式设置这些标志:

if (needsProxy()) {
    System.setProperty("http.proxyHost",getProxyHost());
    System.setProperty("http.proxyPort",getProxyPort());
} else {
    System.setProperty("http.proxyHost","");
    System.setProperty("http.proxyPort","");
}

Just return the right values from the methods needsProxy(), getProxyHost() and getProxyPort() and you can call this code snippet whenever you want.

只需从needsProxy()、getProxyHost()和getProxyPort()方法返回正确的值,您可以随时调用这个代码片段。

#5


10  

You can set some properties about the proxy server as jvm parameters

您可以将代理服务器的一些属性设置为jvm参数

-Dhttp.proxyPort=8080, proxyHost, etc.

-Dhttp。proxyPort = 8080,proxyHost等等。

but if you need pass through an authenticating proxy, you need an authenticator like this example:

但是,如果您需要通过身份验证代理,则需要像下面这个示例那样的身份验证器:

ProxyAuthenticator.java

ProxyAuthenticator.java

import java.net.*;
import java.io.*;

public class ProxyAuthenticator extends Authenticator {

    private String userName, password;

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password.toCharArray());
    }

    public ProxyAuthenticator(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }
}

Example.java

Example.java

    import java.net.Authenticator;
    import ProxyAuthenticator;

public class Example {

    public static void main(String[] args) {
        String username = System.getProperty("proxy.authentication.username");
        String password = System.getProperty("proxy.authentication.password");

                if (username != null && !username.equals("")) {
            Authenticator.setDefault(new ProxyAuthenticator(username, password));
        }

                // here your JVM will be authenticated

    }
}

Based on this reply: http://mail-archives.apache.org/mod_mbox/jakarta-jmeter-user/200208.mbox/%3C494FD350388AD511A9DD00025530F33102F1DC2C@MMSX006%3E

基于此回复:http://mail-archives.apache.org/mod_mbox/jakarta-jmeter- user/200208.mbox/%3c494fd350388ad5dd00025530f33102f1dc2c@mmsx006 %3E

#6


10  

JVM uses the proxy to make HTTP calls

JVM使用代理进行HTTP调用

System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");

This may use user setting proxy

这可以使用用户设置代理

System.setProperty("java.net.useSystemProxies", "true");

#7


8  

reading an XML file and needs to download its schema

读取XML文件并需要下载它的模式

If you are counting on retrieving schemas or DTDs over the internet, you're building a slow, chatty, fragile application. What happens when that remote server hosting the file takes planned or unplanned downtime? Your app breaks. Is that OK?

如果您指望在internet上检索模式或dtd,那么您正在构建一个缓慢、健谈、脆弱的应用程序。当承载文件的远程服务器发生计划停机或计划外停机时,会发生什么情况?你的应用。这样可以吗?

See http://xml.apache.org/commons/components/resolver/resolver-article.html#s.catalog.files

看到http://xml.apache.org/commons/components/resolver/resolver-article.html s.catalog.files

URL's for schemas and the like are best thought of as unique identifiers. Not as requests to actually access that file remotely. Do some google searching on "XML catalog". An XML catalog allows you to host such resources locally, resolving the slowness, chattiness and fragility.

模式和类似的URL被认为是唯一标识符。不是请求远程访问文件。在“XML目录”上进行一些谷歌搜索。一个XML目录允许您在本地托管这些资源,解决慢度、chattiness和脆弱性。

It's basically a permanently cached copy of the remote content. And that's OK, since the remote content will never change. If there's ever an update, it'd be at a different URL. Making the actual retrieval of the resource over the internet especially silly.

它基本上是远程内容的永久缓存副本。这也没关系,因为远程内容永远不会改变。如果有任何更新,它将在不同的URL。使在internet上实际检索资源变得尤其愚蠢。

#8


7  

Set the java.net.useSystemProxies property to true. You can set it, for example, through the JAVA_TOOL_OPTIONS environmental variable. In Ubuntu, you can, for example, add the following line to .bashrc:

将java.net. usesystemproxy属性设置为true。例如,可以通过JAVA_TOOL_OPTIONS环境变量设置它。例如,在Ubuntu中,你可以在。bashrc中添加如下一行:

export JAVA_TOOL_OPTIONS+=" -Djava.net.useSystemProxies=true"

出口JAVA_TOOL_OPTIONS + = " -Djava.net.useSystemProxies = true "

#9


7  

I am also behind firewall, this worked for me!!

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

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();

#10


4  

Add this before you connect to a URL behind a proxy.

在连接到代理的URL之前添加这个。

System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
System.getProperties().put("http.proxyUser", "someUserName");
System.getProperties().put("http.proxyPassword", "somePassword");

#11


4  

This is a minor update, but since Java 7, proxy connections can now be created programmatically rather than through system properties. This may be useful if:

这是一个小的更新,但是由于Java 7,现在可以通过编程而不是通过系统属性创建代理连接。如果:

  1. Proxy needs to be dynamically rotated during the program's runtime
  2. 在程序运行时,需要动态地旋转代理
  3. Multiple parallel proxies need to be used
  4. 需要使用多个并行代理。
  5. Or just make your code cleaner :)
  6. 或者让你的代码更简洁:)

Here's a contrived example in groovy:

groovy中有一个经过设计的示例:

// 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()
}

Full Reference: http://docs.oracle.com/javase/7/docs/technotes/guides/net/proxies.html

全部参考:http://docs.oracle.com/javase/7/docs/technotes/guides/net/proxies.html

#12


4  

The following shows how to set in Java a proxy with proxy user and proxy password from the command line, which is a very common case. You should not save passwords and hosts in the code, as a rule in the first place.

下面显示了如何从命令行中使用代理用户和代理密码在Java中设置代理,这是非常常见的情况。首先,您不应该将密码和主机保存在代码中。

Passing the system properties in command line with -D and setting them in the code with System.setProperty("name", "value") is equivalent.

用-D在命令行中传递系统属性,并用system在代码中设置它们。setProperty(“名字”,“价值”)是等价的。

But note this

但请注意这个

Example that works:

例子:

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

But the following does not work

但是下面的方法行不通

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

The only difference is the position of the system properties ! (before and after the class)

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

If you have special characters in password, you are allowed to put it in quotes "@MyPass123%", like in the above example.

如果密码中有特殊字符,可以将其放在引号“@ passmy123%”中,如上面的示例所示。

If you access an HTTPS service, you have to use https.proxyHost, https.proxyPort etc.

如果访问HTTPS服务,则必须使用HTTPS。proxyHost,https。proxyPort等等。

If you access an HTTP service, you have to use http.proxyHost, http.proxyPort etc.

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

#13


3  

Recently I've discovered the way to allow JVM to use browser proxy settings. What you need to do is to add ${java.home}/lib/deploy.jar to your project and to init the library like the following:

最近我发现了允许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;
    }
}

Afterwards the proxy settings are available to Java API via java.net.ProxySelector.

之后,代理设置通过Java .net. proxyselector对Java API可用。

The only problem with this approach is that you need to start JVM with deploy.jar in bootclasspath e.g. java -Xbootclasspath/a:"%JAVA_HOME%\jre\lib\deploy.jar" -jar my.jar. If somebody knows how to overcome this limitation, let me know.

这种方法的唯一问题是您需要使用deploy启动JVM。jar在bootclasspath,例如java -Xbootclasspath/a:“%JAVA_HOME% jre\lib部署”。jar”jar my.jar。如果有人知道如何克服这个限制,请告诉我。

#14


3  

That works for me:

这工作对我来说:

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: I base on GHad's answer.

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

#15


3  

Combining Sorter's and javabrett/Leonel's answers:

结合Sorter和javabrett/Leonel的回答:

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

#16


1  

As is pointed out in other answers, if you need to use Authenticated proxies, there's no reliable way to do this purely using command-line variables - which is annoying if you're using someone else's application and don't want to mess with the source code.

正如其他答案所指出的,如果您需要使用经过身份验证的代理,那么纯粹使用命令行变量来实现这一点是不可靠的——如果您正在使用其他人的应用程序,并且不想打乱源代码,那么这就很烦人。

Will Iverson makes the helpful suggestion over at Using HttpProxy to connect to a host with preemtive authentication to use a Proxy-management tool such as Proxifier ( http://www.proxifier.com/ for Mac OS X and Windows) to handle this.

Will Iverson在使用HttpProxy连接到具有预先身份验证的主机时给出了有用的建议,使用Proxifier (http://www.proxifier.com/用于Mac OS X和Windows)之类的代理管理工具来处理这个问题。

For example with Proxifier you can set it up to only intercept java commands to be managed and redirected through its (authenticated) proxy. You're going to want to set the proxyHost and proxyPort values to blank in this case though, e.g. pass in -Dhttp.proxyHost= -Dhttp.proxyPort= to your java commands.

例如,对于Proxifier,您可以将其设置为仅拦截要管理的java命令并通过其(已验证的)代理重定向。在这种情况下,您需要将proxyHost和proxyPort值设置为blank,例如传入-Dhttp。proxyHost = -Dhttp。proxyPort=您的java命令。

#17


0  

Also, if you are always looking to download the same schema, then you can add the schema to your classpath (filesystem or JAR), and then use a custom EntityResolver

此外,如果您总是希望下载相同的模式,那么可以将模式添加到类路径(文件系统或JAR)中,然后使用自定义的EntityResolver

See here for a more complete discussion of this approach.

请参阅此处,以便更完整地讨论此方法。

Edit: See @me.yahoo.com/a/0QMxE's discussion of CatalogResolver, which uses the EntityResolver approach:

编辑:参见@me. yahoo.com/a/0qmxeof对目录解析器的讨论,它使用了实体解析器方法:

CatalogResolver cr = new CatalogResolver();
...
yourParser.setEntityResolver(cr) 

#18


0  

You can utilize the http.proxy* JVM variables if you're within a standalone JVM but you SHOULD NOT modify their startup scripts and/or do this within your application server (except maybe jboss or tomcat). Instead you should utilize the JAVA Proxy API (not System.setProperty) or utilize the vendor's own configuration options. Both WebSphere and WebLogic have very defined ways of setting up the proxies that are far more powerful than the J2SE one. Additionally, for WebSphere and WebLogic you will likely break your application server in little ways by overriding the startup scripts (particularly the server's interop processes as you might be telling them to use your proxy as well...).

您可以使用http。如果您在一个独立的JVM中,但是不应该修改它们的启动脚本和/或在您的应用服务器中修改它们(除了jboss或tomcat)。相反,您应该使用JAVA代理API(而不是System.setProperty)或使用供应商自己的配置选项。WebSphere和WebLogic都有非常明确的方法来设置比J2SE代理强大得多的代理。此外,对于WebSphere和WebLogic,通过覆盖启动脚本(尤其是服务器的互操作过程,因为您可能会告诉它们使用您的代理……),您可能会以很小的方式破坏您的应用服务器。

#19


0  

If you want "Socks Proxy", inform the "socksProxyHost" and "socksProxyPort" VM arguments.

如果需要“Socks代理”,请通知“socksProxyHost”和“socksProxyPort”VM参数。

e.g.

如。

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

#20


-3  

I think configuring WINHTTP will also work.

我认为配置WINHTTP也可以。

Many programs including Windows Updates are having problems behind proxy. By setting up WINHTTP will always fix this kind of problems

包括Windows更新在内的许多程序在proxy方面都存在问题。通过设置WINHTTP将始终解决此类问题

#1


290  

From the Java documentation (not the javadoc API):

从Java文档(而不是javadoc API):

http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html

http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html

Set the JVM flags http.proxyHost and http.proxyPort when starting your JVM on the command line. This is usually done in a shell script (in Unix) or bat file (in Windows). Here's the example with the Unix shell script:

设置JVM标记http。proxyHost和http。在命令行上启动JVM时使用proxyPort。这通常是在shell脚本(在Unix中)或bat文件(在Windows中)完成的。下面是Unix shell脚本的示例:

JAVA_FLAGS=-Dhttp.proxyHost=10.0.0.100 -Dhttp.proxyPort=8800
java ${JAVA_FLAGS} ...

When using containers such as JBoss or WebLogic, my solution is to edit the start-up scripts supplied by the vendor.

当使用JBoss或WebLogic等容器时,我的解决方案是编辑供应商提供的启动脚本。

Many developers are familiar with the Java API (javadocs), but many times the rest of the documentation is overlooked. It contains a lot of interesting information: http://download.oracle.com/javase/6/docs/technotes/guides/

许多开发人员都熟悉Java API (javadocs),但是很多时候文档的其余部分都被忽略了。它包含了很多有趣的信息:http://download.oracle.com/javase/6/docs/technotes/guides/


Update : If you do not want to use proxy to resolve some local/intranet hosts, check out the comment from @Tomalak:

更新:如果您不想使用代理解析某些本地/内部网主机,请查看@Tomalak的评论:

Also don't forget the http.nonProxyHosts property!

也不要忘记http。nonProxyHosts财产!

-Dhttp.nonProxyHosts="localhost|127.0.0.1|10.*.*.*|*.foo.com‌​|etc"

#2


73  

To set an HTTP/HTTPS and/or SOCKS proxy programmatically:

以编程方式设置HTTP/HTTPS和/或SOCKS代理:

...

public void setProxy() {
    if (isUseHTTPProxy()) {
        // HTTP/HTTPS Proxy
        System.setProperty("http.proxyHost", getHTTPHost());
        System.setProperty("http.proxyPort", getHTTPPort());
        System.setProperty("https.proxyHost", getHTTPHost());
        System.setProperty("https.proxyPort", getHTTPPort());
        if (isUseHTTPAuth()) {
            String encoded = new String(Base64.encodeBase64((getHTTPUsername() + ":" + getHTTPPassword()).getBytes()));
            con.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
            Authenticator.setDefault(new ProxyAuth(getHTTPUsername(), getHTTPPassword()));
        }
    }
    if (isUseSOCKSProxy()) {
        // SOCKS Proxy
        System.setProperty("socksProxyHost", getSOCKSHost());
        System.setProperty("socksProxyPort", getSOCKSPort());
        if (isUseSOCKSAuth()) {
            System.setProperty("java.net.socks.username", getSOCKSUsername());
            System.setProperty("java.net.socks.password", getSOCKSPassword());
            Authenticator.setDefault(new ProxyAuth(getSOCKSUsername(), getSOCKSPassword()));
        }
    }
}

...

public class ProxyAuth extends Authenticator {
    private PasswordAuthentication auth;

    private ProxyAuth(String user, String password) {
        auth = new PasswordAuthentication(user, password == null ? new char[]{} : password.toCharArray());
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return auth;
    }
}

...

Remember that HTTP proxies and SOCKS proxies operate at different levels in the network stack, so you can use one or the other or both.

请记住,HTTP代理和SOCKS代理在网络堆栈中的不同级别上操作,因此您可以使用一个或另一个或两个。

#3


72  

To use the system proxy setup:

使用系统代理设置:

java -Djava.net.useSystemProxies=true ...

Or programatically:

或编程:

System.setProperty("java.net.useSystemProxies", "true");

Source: http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html

来源:http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html

#4


37  

You can set those flags programmatically this way:

您可以通过编程方式设置这些标志:

if (needsProxy()) {
    System.setProperty("http.proxyHost",getProxyHost());
    System.setProperty("http.proxyPort",getProxyPort());
} else {
    System.setProperty("http.proxyHost","");
    System.setProperty("http.proxyPort","");
}

Just return the right values from the methods needsProxy(), getProxyHost() and getProxyPort() and you can call this code snippet whenever you want.

只需从needsProxy()、getProxyHost()和getProxyPort()方法返回正确的值,您可以随时调用这个代码片段。

#5


10  

You can set some properties about the proxy server as jvm parameters

您可以将代理服务器的一些属性设置为jvm参数

-Dhttp.proxyPort=8080, proxyHost, etc.

-Dhttp。proxyPort = 8080,proxyHost等等。

but if you need pass through an authenticating proxy, you need an authenticator like this example:

但是,如果您需要通过身份验证代理,则需要像下面这个示例那样的身份验证器:

ProxyAuthenticator.java

ProxyAuthenticator.java

import java.net.*;
import java.io.*;

public class ProxyAuthenticator extends Authenticator {

    private String userName, password;

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password.toCharArray());
    }

    public ProxyAuthenticator(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }
}

Example.java

Example.java

    import java.net.Authenticator;
    import ProxyAuthenticator;

public class Example {

    public static void main(String[] args) {
        String username = System.getProperty("proxy.authentication.username");
        String password = System.getProperty("proxy.authentication.password");

                if (username != null && !username.equals("")) {
            Authenticator.setDefault(new ProxyAuthenticator(username, password));
        }

                // here your JVM will be authenticated

    }
}

Based on this reply: http://mail-archives.apache.org/mod_mbox/jakarta-jmeter-user/200208.mbox/%3C494FD350388AD511A9DD00025530F33102F1DC2C@MMSX006%3E

基于此回复:http://mail-archives.apache.org/mod_mbox/jakarta-jmeter- user/200208.mbox/%3c494fd350388ad5dd00025530f33102f1dc2c@mmsx006 %3E

#6


10  

JVM uses the proxy to make HTTP calls

JVM使用代理进行HTTP调用

System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");

This may use user setting proxy

这可以使用用户设置代理

System.setProperty("java.net.useSystemProxies", "true");

#7


8  

reading an XML file and needs to download its schema

读取XML文件并需要下载它的模式

If you are counting on retrieving schemas or DTDs over the internet, you're building a slow, chatty, fragile application. What happens when that remote server hosting the file takes planned or unplanned downtime? Your app breaks. Is that OK?

如果您指望在internet上检索模式或dtd,那么您正在构建一个缓慢、健谈、脆弱的应用程序。当承载文件的远程服务器发生计划停机或计划外停机时,会发生什么情况?你的应用。这样可以吗?

See http://xml.apache.org/commons/components/resolver/resolver-article.html#s.catalog.files

看到http://xml.apache.org/commons/components/resolver/resolver-article.html s.catalog.files

URL's for schemas and the like are best thought of as unique identifiers. Not as requests to actually access that file remotely. Do some google searching on "XML catalog". An XML catalog allows you to host such resources locally, resolving the slowness, chattiness and fragility.

模式和类似的URL被认为是唯一标识符。不是请求远程访问文件。在“XML目录”上进行一些谷歌搜索。一个XML目录允许您在本地托管这些资源,解决慢度、chattiness和脆弱性。

It's basically a permanently cached copy of the remote content. And that's OK, since the remote content will never change. If there's ever an update, it'd be at a different URL. Making the actual retrieval of the resource over the internet especially silly.

它基本上是远程内容的永久缓存副本。这也没关系,因为远程内容永远不会改变。如果有任何更新,它将在不同的URL。使在internet上实际检索资源变得尤其愚蠢。

#8


7  

Set the java.net.useSystemProxies property to true. You can set it, for example, through the JAVA_TOOL_OPTIONS environmental variable. In Ubuntu, you can, for example, add the following line to .bashrc:

将java.net. usesystemproxy属性设置为true。例如,可以通过JAVA_TOOL_OPTIONS环境变量设置它。例如,在Ubuntu中,你可以在。bashrc中添加如下一行:

export JAVA_TOOL_OPTIONS+=" -Djava.net.useSystemProxies=true"

出口JAVA_TOOL_OPTIONS + = " -Djava.net.useSystemProxies = true "

#9


7  

I am also behind firewall, this worked for me!!

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

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();

#10


4  

Add this before you connect to a URL behind a proxy.

在连接到代理的URL之前添加这个。

System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
System.getProperties().put("http.proxyUser", "someUserName");
System.getProperties().put("http.proxyPassword", "somePassword");

#11


4  

This is a minor update, but since Java 7, proxy connections can now be created programmatically rather than through system properties. This may be useful if:

这是一个小的更新,但是由于Java 7,现在可以通过编程而不是通过系统属性创建代理连接。如果:

  1. Proxy needs to be dynamically rotated during the program's runtime
  2. 在程序运行时,需要动态地旋转代理
  3. Multiple parallel proxies need to be used
  4. 需要使用多个并行代理。
  5. Or just make your code cleaner :)
  6. 或者让你的代码更简洁:)

Here's a contrived example in groovy:

groovy中有一个经过设计的示例:

// 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()
}

Full Reference: http://docs.oracle.com/javase/7/docs/technotes/guides/net/proxies.html

全部参考:http://docs.oracle.com/javase/7/docs/technotes/guides/net/proxies.html

#12


4  

The following shows how to set in Java a proxy with proxy user and proxy password from the command line, which is a very common case. You should not save passwords and hosts in the code, as a rule in the first place.

下面显示了如何从命令行中使用代理用户和代理密码在Java中设置代理,这是非常常见的情况。首先,您不应该将密码和主机保存在代码中。

Passing the system properties in command line with -D and setting them in the code with System.setProperty("name", "value") is equivalent.

用-D在命令行中传递系统属性,并用system在代码中设置它们。setProperty(“名字”,“价值”)是等价的。

But note this

但请注意这个

Example that works:

例子:

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

But the following does not work

但是下面的方法行不通

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

The only difference is the position of the system properties ! (before and after the class)

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

If you have special characters in password, you are allowed to put it in quotes "@MyPass123%", like in the above example.

如果密码中有特殊字符,可以将其放在引号“@ passmy123%”中,如上面的示例所示。

If you access an HTTPS service, you have to use https.proxyHost, https.proxyPort etc.

如果访问HTTPS服务,则必须使用HTTPS。proxyHost,https。proxyPort等等。

If you access an HTTP service, you have to use http.proxyHost, http.proxyPort etc.

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

#13


3  

Recently I've discovered the way to allow JVM to use browser proxy settings. What you need to do is to add ${java.home}/lib/deploy.jar to your project and to init the library like the following:

最近我发现了允许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;
    }
}

Afterwards the proxy settings are available to Java API via java.net.ProxySelector.

之后,代理设置通过Java .net. proxyselector对Java API可用。

The only problem with this approach is that you need to start JVM with deploy.jar in bootclasspath e.g. java -Xbootclasspath/a:"%JAVA_HOME%\jre\lib\deploy.jar" -jar my.jar. If somebody knows how to overcome this limitation, let me know.

这种方法的唯一问题是您需要使用deploy启动JVM。jar在bootclasspath,例如java -Xbootclasspath/a:“%JAVA_HOME% jre\lib部署”。jar”jar my.jar。如果有人知道如何克服这个限制,请告诉我。

#14


3  

That works for me:

这工作对我来说:

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: I base on GHad's answer.

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

#15


3  

Combining Sorter's and javabrett/Leonel's answers:

结合Sorter和javabrett/Leonel的回答:

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

#16


1  

As is pointed out in other answers, if you need to use Authenticated proxies, there's no reliable way to do this purely using command-line variables - which is annoying if you're using someone else's application and don't want to mess with the source code.

正如其他答案所指出的,如果您需要使用经过身份验证的代理,那么纯粹使用命令行变量来实现这一点是不可靠的——如果您正在使用其他人的应用程序,并且不想打乱源代码,那么这就很烦人。

Will Iverson makes the helpful suggestion over at Using HttpProxy to connect to a host with preemtive authentication to use a Proxy-management tool such as Proxifier ( http://www.proxifier.com/ for Mac OS X and Windows) to handle this.

Will Iverson在使用HttpProxy连接到具有预先身份验证的主机时给出了有用的建议,使用Proxifier (http://www.proxifier.com/用于Mac OS X和Windows)之类的代理管理工具来处理这个问题。

For example with Proxifier you can set it up to only intercept java commands to be managed and redirected through its (authenticated) proxy. You're going to want to set the proxyHost and proxyPort values to blank in this case though, e.g. pass in -Dhttp.proxyHost= -Dhttp.proxyPort= to your java commands.

例如,对于Proxifier,您可以将其设置为仅拦截要管理的java命令并通过其(已验证的)代理重定向。在这种情况下,您需要将proxyHost和proxyPort值设置为blank,例如传入-Dhttp。proxyHost = -Dhttp。proxyPort=您的java命令。

#17


0  

Also, if you are always looking to download the same schema, then you can add the schema to your classpath (filesystem or JAR), and then use a custom EntityResolver

此外,如果您总是希望下载相同的模式,那么可以将模式添加到类路径(文件系统或JAR)中,然后使用自定义的EntityResolver

See here for a more complete discussion of this approach.

请参阅此处,以便更完整地讨论此方法。

Edit: See @me.yahoo.com/a/0QMxE's discussion of CatalogResolver, which uses the EntityResolver approach:

编辑:参见@me. yahoo.com/a/0qmxeof对目录解析器的讨论,它使用了实体解析器方法:

CatalogResolver cr = new CatalogResolver();
...
yourParser.setEntityResolver(cr) 

#18


0  

You can utilize the http.proxy* JVM variables if you're within a standalone JVM but you SHOULD NOT modify their startup scripts and/or do this within your application server (except maybe jboss or tomcat). Instead you should utilize the JAVA Proxy API (not System.setProperty) or utilize the vendor's own configuration options. Both WebSphere and WebLogic have very defined ways of setting up the proxies that are far more powerful than the J2SE one. Additionally, for WebSphere and WebLogic you will likely break your application server in little ways by overriding the startup scripts (particularly the server's interop processes as you might be telling them to use your proxy as well...).

您可以使用http。如果您在一个独立的JVM中,但是不应该修改它们的启动脚本和/或在您的应用服务器中修改它们(除了jboss或tomcat)。相反,您应该使用JAVA代理API(而不是System.setProperty)或使用供应商自己的配置选项。WebSphere和WebLogic都有非常明确的方法来设置比J2SE代理强大得多的代理。此外,对于WebSphere和WebLogic,通过覆盖启动脚本(尤其是服务器的互操作过程,因为您可能会告诉它们使用您的代理……),您可能会以很小的方式破坏您的应用服务器。

#19


0  

If you want "Socks Proxy", inform the "socksProxyHost" and "socksProxyPort" VM arguments.

如果需要“Socks代理”,请通知“socksProxyHost”和“socksProxyPort”VM参数。

e.g.

如。

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

#20


-3  

I think configuring WINHTTP will also work.

我认为配置WINHTTP也可以。

Many programs including Windows Updates are having problems behind proxy. By setting up WINHTTP will always fix this kind of problems

包括Windows更新在内的许多程序在proxy方面都存在问题。通过设置WINHTTP将始终解决此类问题