将JVM / JRE设置为自动使用Windows代理 [英] Setting JVM/JRE to use Windows Proxy Automatically

查看:132
本文介绍了将JVM / JRE设置为自动使用Windows代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实看到了关于为JVM设置代理的问题,但我想问的是如何使用已经配置的代理(在Windows上)。

I did see the question about setting the proxy for the JVM but what I want to ask is how one can utilize the proxy that is already configured (on Windows).

以下是我的问题的演示:

Here is a demonstration of my issue:




  1. 转到您的控件Panel-> Java并设置代理地址。

  2. 运行以下简单的applet代码(我正在使用Eclipse IDE):





import java.awt.Graphics;
import javax.swing.JApplet;
import java.util.*;

public class Stacklet extends JApplet {
    private String message;
    public void init(){
        Properties props = System.getProperties();
        message = props.getProperty("http.proxyHost", "NONE");      
        message = (message.length() == 0)? "NONE": message;
    }

    public void paint(Graphics g)
    {
        g.drawString(message, 20, 20);
    }
}

Applet显示NONE而不考虑设置你已经放入了Java控制面板。如果Windows代理设置(通常在Internet Explorer中设置)是我可以确定的,但在Java控制面板中执行额外的配置步骤仍然是可接受的解决方案,那将是最好的。

The Applet displays "NONE" without regard to the settings you've placed in the Java Control Panel. What would be best would be if the Windows proxy settings (usually set in Internet Explorer) were what I could determine but doing an extra configuration step in the Java Control Panel would still be an acceptable solution.

谢谢!

推荐答案

可以使用 ProxySelector 类并通过使用 System类的setProperty方法:

It is possible to detect the proxy using the ProxySelector class and assign the system proxy by assigning environment variables with the setProperty method of the System class:

System.setProperty("java.net.useSystemProxies", "true");
System.out.println("detecting proxies");
List l = null;
try {
    l = ProxySelector.getDefault().select(new URI("http://foo/bar"));
} 
catch (URISyntaxException e) {
    e.printStackTrace();
}
if (l != null) {
    for (Iterator iter = l.iterator(); iter.hasNext();) {
        java.net.Proxy proxy = (java.net.Proxy) iter.next();
        System.out.println("proxy type: " + proxy.type());

        InetSocketAddress addr = (InetSocketAddress) proxy.address();

        if (addr == null) {
            System.out.println("No Proxy");
        } else {
            System.out.println("proxy hostname: " + addr.getHostName());
            System.setProperty("http.proxyHost", addr.getHostName());
            System.out.println("proxy port: " + addr.getPort());
            System.setProperty("http.proxyPort", Integer.toString(addr.getPort()));
        }
    }
}

这篇关于将JVM / JRE设置为自动使用Windows代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆