El Lord Code El Lord Code - 4 months ago 33
Java Question

Non proxy hosts for OkHttp3

How can I set what hostnames should not pass in one request made by

OkHttpClient
using a proxy?

Is there anything equivalent for the vm argument
-Dhttp.nonProxyHosts
in OkHttp3?

For example:

final OkHttpClient okHttpClient = new OkHttpClient
.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.proxy(new Proxy(Proxy.Type.HTTP,
new InetSocketAddress(defaultProxyHostName, Integer.parseInt(defaultProxyPort))))
.build();

Answer

After digging around a bit, I have found out how to do it.

So I had to create a ProxySelector implementing the logic when the proxy should be applied or not.

Example:

final ProxySelector proxySelector = new ProxySelector() {
    @Override
    public java.util.List<Proxy> select(final URI uri) {
        final List<Proxy> proxyList = new ArrayList<Proxy>(1);

        // Host
        final String host = uri.getHost();

        // Is an internal host
        if (host.startsWith("127.0.0.1") || StringUtils.contains(nonProxyHostsValue, host)) {
            proxyList.add(Proxy.NO_PROXY);
        } else {
            // Add proxy
            proxyList.add(new Proxy(Type.HTTP,
                    new InetSocketAddress(proxyHostNameValue, Integer.parseInt(proxyPortValue))));
        }

        return proxyList;
    }

    @Override
    public void connectFailed(URI arg0, SocketAddress arg1, IOException arg2) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
};

// Set proxy selector
okHttpClientBuilder.proxySelector(proxySelector);
Comments