Last active
August 29, 2015 14:16
-
-
Save double16/17128e4c93994fc0fd89 to your computer and use it in GitHub Desktop.
Java proxy for specific URLs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.net.InetSocketAddress; | |
import java.net.Proxy; | |
import java.net.Proxy.Type; | |
import java.net.ProxySelector; | |
import java.net.SocketAddress; | |
import java.net.URI; | |
import java.util.Collections; | |
import java.util.List; | |
import org.apache.log4j.Logger; | |
public class ParosProxySelector extends ProxySelector { | |
private static final Logger log = Logger.getLogger(ParosProxySelector.class); | |
private static final Proxy PAROS_PROXY, SOCKS_PROXY; | |
static { | |
PAROS_PROXY = new Proxy(Type.HTTP, new InetSocketAddress("localhost", 8080)); | |
SOCKS_PROXY = new Proxy(Type.SOCKS, new InetSocketAddress("localhost", 1080)); | |
} | |
public static ProxySelector proxyFor(String uriBase) { | |
ProxySelector existing = ProxySelector.getDefault(); | |
ProxySelector newProxy = new ParosProxySelector(uriBase, existing); | |
ProxySelector.setDefault(newProxy); | |
return newProxy; | |
} | |
private final String uriBase; | |
private final ProxySelector chained; | |
protected ParosProxySelector(String uriBase, ProxySelector chained) { | |
this.uriBase = uriBase; | |
this.chained = chained; | |
} | |
@Override | |
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { | |
log.error("Proxy failure for "+uri.toASCIIString()); | |
} | |
@Override | |
public List<Proxy> select(URI uri) { | |
final String uriStr = uri.toASCIIString(); | |
System.err.println("ParosProxySelector.select("+uriStr+")"); | |
if (uriStr.contains("localhost:1080") | |
|| uriStr.contains("127.0.0.1:1080") | |
|| uriStr.contains("localhost:8080") | |
|| uriStr.contains("127.0.0.1:8080")) { | |
return Collections.singletonList(Proxy.NO_PROXY); | |
} | |
if (uriStr.contains(uriBase)) { | |
if (uri.getScheme().equals("http")) { | |
return Collections.singletonList(PAROS_PROXY); | |
} | |
if (uri.getScheme().equals("socket")) { | |
return Collections.singletonList(SOCKS_PROXY); | |
} | |
} | |
if (chained != null) { | |
return chained.select(uri); | |
} | |
return Collections.singletonList(Proxy.NO_PROXY); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment