How to use automatic proxy configuration script in Java
Asked Answered
H

4

10

My Internet Explorer is set to have an automatic proxy file(so-called PAC) for web access. Is there a way to use this on my Java program, also ?

My below Java code does not seem to use proxy at all.

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.
}

I also set my proxy script on Java Control Panel(Control->Java), but the same result. and I found there's no way to set PAC file for Java programmatically.

People use http.proxyHost for System.setProperties(..) but this is a only for setting proxy host, not proxy script(PAC file).

Hydrokinetic answered 7/6, 2012 at 16:50 Comment(0)
H
9

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

Hydrokinetic answered 8/6, 2012 at 15:27 Comment(3)
Seems you have a DummyAutoProxyHandler class with Pixie dust on it.Embrasure
could you give link to download this libRebeckarebeka
Needed SunAutoProxyHandler (as in another answer) and policy.all file as described in this article. That is: grant { permission java.security.AllPermission "", ""; }; in policy.all and in Java add System.setProperty("java.security.policy" , "policy.all");.Endive
C
2

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.

Comfy answered 7/6, 2012 at 20:7 Comment(0)
E
1

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

Eburnation answered 25/11, 2013 at 0:21 Comment(0)
W
1

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());
    }
Whiteeye answered 29/4, 2016 at 11:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.