3

I'm creating a default HTTP client using HttpClients.createDefault(), but I'd like to change the default timeout (it seems pretty long, it's been over a minute now and it didn't time out).

Is it possible to change only the timeout of the default client or do I have to build the client from scratch?

I'm using version 4.3.3 of the apache HTTP client.

2
  • see also stackoverflow.com/questions/3000214/… Commented Apr 4, 2014 at 14:01
  • @robermann I've checked the code in that answer. Using the code example there gives me deprecated warnings in eclipse. Commented Apr 4, 2014 at 14:03

2 Answers 2

9

Why using the default client when timeouts are easily configurable for custom clients? The following code does the job for httpclient 4.3.4.

final RequestConfig requestConfig = RequestConfig.custom()
    .setConnectTimeout(CONNTECTION_TIMEOUT_MS)
    .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT_MS)
    .setSocketTimeout(SOCKET_TIMEOUT_MS)
    .build();
final CloseableHttpClient httpclient = HttpClients.custom()
    .setDefaultRequestConfig(requestConfig)
    .build();
Sign up to request clarification or add additional context in comments.

1 Comment

What are the default values in the Apache code? Are any constants/symbols available?
5
HostConfiguration hostCfg = new HostConfiguration();
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("... your get query string");

int timeout = 5000; //config your value
method.getParams().setSoTimeout(timeout);

//the call
client.executeMethod(hostCfg, method);

Or you can set the timeout in HttpConnectionParams.

EDIT

With HttpClient = 4.3, from the official documentation:

HttpClientContext clientContext = HttpClientContext.create();
PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();
Socket socket = sf.createSocket(clientContext);

int timeout = 1000; // ms <-- 

HttpHost target = new HttpHost("localhost");
InetSocketAddress remoteAddress = new InetSocketAddress(InetAddress.getByAddress(new byte[] {127,0,0,1}), 80);
sf.connectSocket(timeout, socket, target, remoteAddress, null, clientContext);

4 Comments

Is it possible that this is for version 3.x of the apache client? I'm using version 4.3.3, should have mentioned that - my bad :(
I'm still getting the deprecated warning ("The type HttpParams is deprecated" for example)
HttpClient is really heavily changed. Added a 4.3's example code
Thanks for the 4.3 example. I've also found a solution using the RequestConfig method setConnectionTimeout, and assigning that config using the method setConfig on the httpget object :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.