How to use automatic proxy configuration script in Java

谁都会走 提交于 2019-11-30 12:42:38

Wow! I could load Proxy Auto-Config (PAC) file on Java. Please see below codes and package.

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

You already have a [com.sun.deploy.net.proxy] package on your machine! Find [deploy.jar] ;D

Michael-O

Java does not have any built-in support for parsing the JS PAC file. You are on your own. What you can do is download that file and parse the proxy host from it. You should read this.

In my case, I've just figured-out what the .pac file will return, then hardcode.

Based on @Jaeh answer I used the code below. Note that SunAutoProxyHandler implements AbstractAutoProxyHandler and there is an alternative concrete implementation called PluginAutoProxyHandler but that implementation does not appear to be as robust:

    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());
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!