Edwin Dalorzo Edwin Dalorzo - 2 months ago 85
Java Question

How to set proxy for Spring AsyncRestTemplate using Netty4ClientHttpRequestFactory?

When I use a SimpleRequestFactory with my AsyncRestTemplate I can easily configure an HTTP proxy server.

I can either do (sample code in Kotlin):

@Bean
open fun asyncRestTemplate(): AsyncRestTemplate {
val proxy = Proxy(Proxy.Type.HTTP, InetSocketAddress("127.0.0.1", 8008))

val requestFactory = SimpleClientHttpRequestFactory().apply {
this.setConnectTimeout(TimeUnit.SECONDS.toMillis(10).toInt())
this.setReadTimeout(TimeUnit.SECONDS.toMillis(10).toInt())
this.setProxy(proxy)
this.setTaskExecutor(taskExecutor())
}

return AsyncRestTemplate(requestFactory)
}


Or I can simply set the corresponding system properties:
-Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=8008
.

However, in the moment that I switch from the
SimpleClientHttpRequestFactory
to a
Netty4ClientHttpRequestFactory
there is no evident way to configure the proxy directly and it seems this client does not respect the system properties either.

val requestFactory = Netty4ClientHttpRequestFactory().apply {
this.setConnectTimeout(TimeUnit.SECONDS.toMillis(10).toInt())
this.setReadTimeout(TimeUnit.SECONDS.toMillis(10).toInt())
//this.setProxy(proxy) //???
}


Once I change for the netty client, I have no clue on how to make it go through the proxy.

My interest in using the netty client was that I not only wanted to make async requests, but also I wanted this to be non-blocking. I hope I'm not making a wrong assumption here.

Does anyone know how can I use a proxy server when using the
Netty4ClientHttpRequestFactory
or perhaps know of an alternative non-blocking client supported by Spring that I could use?

Answer

The Netty4ClientHttpRequestFactory (source) and related classes such as Netty4ClientHttpRequest (source) use SimpleChannelInboundHandler for the channel and do not use the proxy handler. Everything is private and unable to be overridden within the source, so there is no way to change it to support Proxies. You would have to almost rewrite the whole thing.

You have other async client options that will work very well and allow you more configuration options. The included Netty one is fairly basic anyway. OkHttpClientHttpRequestFactory and HttpComponentsAsyncClientHttpRequestFactory both let you pass in your own configured client.

Comments