Configuring Timeout with Apache HttpClient 4.0

Great news everyone: just recently an all-new version of Apache HttpClient was released. HttpClient is now part of the new initiative Apache HttpComponents, which seems to aim for a complete approach to Http programming in Java; server side as well as client side.

I’ve used Commons HttpClient in older versions on several occasions in the past and have found it to be extremely useful. I’ve only just started working with the new version, but there seems to quite a lot of good stuff in there. For example I’m thrilled to see that the Template pattern, heavily used in Spring, has now made its way to the Apache world (e.g. ResponseHandler, a callback interface to be used with HttpClient for handling results).

Now, configuration of HttpClient has always been a little bit tricky. There are so many features in there, and most of these are configured using generic parameters (HttpParams), basically name-value pairs of a setting identifier and its value. This has not been made that much easier in the new version.

In my current project I was struggling to find the appropriate parameters for configuring timeouts with the new version of the framework. It turned out to be quite difficult to find clear information on this – the documentation on the 4.0 version of HttpClient is still quite sparse. Since it took me a while to find out how to do this I figured I wasn’t alone, so here goes:

My original solution for this problem – being completely unable to find the proper way to do it – was to use the hard-coded property values and set them as parameters in HttpParams. Fortunately, a reader with signature ‘BoD’ (see below) knew the right way to do this and was kind enough to share.

Well, If you guys are lazy and want auto generation of your Apache HttpClient code, use HTTP4E:

It is an awesome Eclipse plugin. It has tabs, syntax coloring, auto suggest, and most importantly you can create an HTTP, REST call in 5 seconds. And when you have an HTTP call the one-click Java code generation just rocks. The code generated is pure Apache HttpClient code, as the tool is build on top of Apache HttpClient.

Specifying source route:
ConnRoutePNames.LOCAL_ADDRESS=’http.route.local-address': defines a local address to be used by all default route planner. On machines with multiple network interfaces, this parameter can be used to select the network interface from which the connection originates. This parameter expects a value of type java.net.InetAddress. If this parameter is not set, a default local address will be used automatically.

“Please note that HttpClient instances created with HttpClientBuilder or HttpClients [which is now the only valid way to create any instances] are immutable. Their configuration can no longer be altered.”

So, the only way to go now is to create a RequestConfig and feed it to the _request_ via HttpRequestBase.setConfig.

I have no idea why it was made to work like that, but that’s how it is…