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.

Ahatius
  • 4,777
  • 11
  • 49
  • 79
  • see also http://stackoverflow.com/questions/3000214/java-http-client-request-with-defined-timeout – robermann Apr 04 '14 at 14:01
  • @robermann I've checked the code in that answer. Using the code example there gives me deprecated warnings in eclipse. – Ahatius Apr 04 '14 at 14:03

2 Answers2

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();
RedXIII
  • 781
  • 7
  • 6
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);
robermann
  • 1,722
  • 10
  • 19
  • 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 :( – Ahatius Apr 04 '14 at 14:01
  • I'm still getting the deprecated warning ("The type HttpParams is deprecated" for example) – Ahatius Apr 04 '14 at 19:10
  • HttpClient is really heavily changed. Added a 4.3's example code – robermann Apr 06 '14 at 12:46
  • 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 :) – Ahatius Apr 06 '14 at 15:40