Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 900
Carlos Alberto Avatar asked Jul 01 '16 22:07

Carlos Alberto


2 Answers

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);
like image 81
Carlos Alberto Avatar answered Nov 20 '22 06:11

Carlos Alberto


The API you're looking for is ProxySelector. You can configure this on your OkHttpClient.

like image 1
Jesse Wilson Avatar answered Nov 20 '22 07:11

Jesse Wilson