Reputation: 795
I'm using Apache HttpClient 4.5 (with fluent interface) in a Java console application. I noticed, that its default timeout value seem to be infinite, but i have to use a non-infinite timeout value for the requests i send. And i would like to use the same timeout value for all requests.
How do i globally set the default connection-timeout and socket-timeout values, so that i do not have to set them every place in the code where i send a request? (Remember i use the fluent interface)
Example:
Right now, each place in my code where i send a request i do something like: (simple example)
HttpResponse response = Request.Get(url)
.connectionTimeout(CONNECTION_TIMEOUT) // <- want to get rid of this
.sessionTimeout(SESSION_TIMEOUT) // <- and this
.execute()
.returnResponse();
What i would like to do, is to set the default value once and for all, at the beginning of my program. Something like:
SomeImaginaryConfigClass.setDefaultConnectionTimeout(CONNECTION_TIMEOUT);
SomeImaginaryConfigClass.setDefaultSessionTimeout(SESSION_TIMEOUT);
so that i can just send a request like this
HttpResponse response = Request.Get(url).execute().returnResponse();
without setting the timeout parameters on every single call.
I have seen some answers on the net, but they're either for old versions of Apache HttpClient (i.e. doesn't work), or they talk about using a builder or passing a config class along or other approaches way too complicated for my needs. I just want to set the default timeout values, nothing fancier than that. Where do i do this?
Upvotes: 3
Views: 9911
Reputation: 27538
One could use a custom Executor
to do so
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setSocketTimeout(5000)
.build();
SocketConfig socketConfig = SocketConfig.custom()
.setSoTimeout(5000)
.build();
CloseableHttpClient client = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setDefaultSocketConfig(socketConfig)
.build();
Executor executor = Executor.newInstance(client);
executor.execute(Request.Get("http://thishost/")).returnResponse();
executor.execute(Request.Get("http://thathost/")).returnResponse();
Upvotes: 8