【问题标题】:How to use automatic proxy configuration script in Java如何在 Java 中使用自动代理配置脚本
【发布时间】:2012-06-11 18:29:35
【问题描述】:

我的 Internet Explorer 设置为具有用于 Web 访问的自动代理文件(所谓的 PAC)。有没有办法在我的 Java 程序上使用它?

我下面的 Java 代码似乎根本没有使用代理。

ArrayList<Proxy> ar = new ArrayList<Proxy>(ProxySelector.getDefault().select(new URI("http://service.myurlforproxy.com")));
for(Proxy p : ar){
  System.out.println(p.toString()); //output is just DIRECT T.T it should be PROXY.
}

我还在 Java 控制面板(Control->Java)上设置了我的代理脚本,但结果相同。 而且我发现无法以编程方式为 Java 设置 PAC 文件。

人们将 http.proxyHost 用于 System.setProperties(..) 但这仅用于设置代理主机,而不是代理脚本(PAC 文件)。

【问题讨论】:

    标签: java proxy pac


    【解决方案1】:

    Java 没有对解析 JS PAC 文件的任何内置支持。你只能靠自己。您可以做的是下载该文件并从中解析代理主机。你应该阅读this

    【讨论】:

      【解决方案2】:

      哇!我可以在 Java 上加载代理自动配置 (PAC) 文件。请看下面的代码和包。

      import com.sun.deploy.net.proxy.*;
      .
      .
      BrowserProxyInfo b = new BrowserProxyInfo();        
      b.setType(ProxyType.AUTO);
      b.setAutoConfigURL("http://yourhost/proxy.file.pac");       
      DummyAutoProxyHandler handler = new DummyAutoProxyHandler();
      handler.init(b);
      
      URL url = new URL("http://host_to_query");
      ProxyInfo[] ps = handler.getProxyInfo(url);     
      for(ProxyInfo p : ps){
          System.out.println(p.toString());
      }
      

      您的机器上已经有一个 [com.sun.deploy.net.proxy] 包! 找到 [deploy.jar] ;D

      【讨论】:

      • 好像你有一个 DummyAutoProxyHandler 类,上面有 Pixie 灰尘。
      • 你能给个链接下载这个库吗
      • 需要SunAutoProxyHandler(如另一个答案)和policy.all文件,如this article中所述。即:grant { permission java.security.AllPermission "", ""; };policy.all 中,在Java 中添加System.setProperty("java.security.policy" , "policy.all");
      【解决方案3】:

      就我而言,我刚刚弄清楚 .pac 文件将返回什么,然后进行硬编码。

      【讨论】:

        【解决方案4】:

        根据@Jaeh 的回答,我使用了下面的代码。 请注意,SunAutoProxyHandler 实现了 AbstractAutoProxyHandler,还有一个替代的具体实现称为 PluginAutoProxyHandler,但该实现似乎并不那么健壮:

            BrowserProxyInfo b = new BrowserProxyInfo();
            b.setType(ProxyType.AUTO);
            b.setAutoConfigURL("http://example.com/proxy.pac");
        
            SunAutoProxyHandler handler = new SunAutoProxyHandler();
            handler.init(b);
        
            ProxyInfo[] ps = handler.getProxyInfo(new URL(url));
            for(ProxyInfo p : ps){
                System.out.println(p.toString());
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-09-17
          • 1970-01-01
          • 2018-07-01
          • 2012-05-06
          • 1970-01-01
          • 1970-01-01
          • 2018-02-16
          • 2017-03-21
          相关资源
          最近更新 更多