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();
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.
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);
The API you're looking for is ProxySelector. You can configure this on your OkHttpClient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With