Last Updated: February 25, 2016
· lizell

Setting a global http(s) proxy programmatically in Java

Here is a way to set a global proxy in Java when you can not control how your third party code communicates. Put this static block somewhere in a class that is loaded by your application.

This is also available as a gist.

static {
    ProxySelector.setDefault(new ProxySelector() {
        private final ProxySelector def = ProxySelector.getDefault();

        public List<Proxy> select(final URI uri) {
            if ("http".equalsIgnoreCase(uri.getScheme()) || "socket".equalsIgnoreCase(uri.getScheme())) {
            if (uri.getHost().contains("<changeme>")) {
                // Using proxy for <changeme> call
                return Arrays.asList(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("", 8889)));


    public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) {
        throw new UnsupportedOperationException("Not supported yet.");