Question

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.

Was it helpful?

Solution 2

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);

OTHER TIPS

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top