I would like to make BIT (Built in tests) to a number of server in my cloud. I need the request to fail on large timeout.
How should I do this with java?
Trying something like the below does not seem to work.
public class TestNodeAliveness {
public static NodeStatus nodeBIT(String elasticIP) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
client.getParams().setIntParameter("http.connection.timeout", 1);
HttpUriRequest request = new HttpGet("http://192.168.20.43");
HttpResponse response = client.execute(request);
System.out.println(response.toString());
return null;
}
public static void main(String[] args) throws ClientProtocolException, IOException {
nodeBIT("");
}
}
-- EDIT: Clarify what library is being used --
I'm using httpclient from apache, here is the relevant pom.xml section
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.0.1</version>
<type>jar</type>
</dependency>
HttpParams is deprecated in the new Apache HTTPClient library. Using the code provided by Laz leads to deprecation warnings.
I suggest to use RequestConfig instead on your HttpGet or HttpPost instance:
If you are using Http Client version 4.3 and above you should be using this:
I found that setting the time out settings in
HttpConnectionParams
andHttpConnectionManager
did not solve our case. We're limited to usingorg.apache.commons.httpclient
version 3.0.1.I ended up using an
java.util.concurrent.ExecutorService
to monitor theHttpClient.executeMethod()
call.Here's a small, self-contained example
It looks like you are using the HttpClient API, which I know nothing about, but you could write something similar to this using core Java.
HttpConnectionParams.setSoTimeout(params, 10*60*1000);// for 10 mins i have set the timeout
You can as well define your required time out.
This was already mentioned in a comment by benvoliot above. But, I think it's worth a top-level post because it sure had me scratching my head. I'm posting this in case it helps someone else out.
I wrote a simple test client and the
CoreConnectionPNames.CONNECTION_TIMEOUT
timeout works perfectly in that case. The request gets canceled if the server doesn't respond.Inside the server code I was actually trying to test however, the identical code never times out.
Changing it to time out on the socket connection activity (
CoreConnectionPNames.SO_TIMEOUT
) rather than the HTTP connection (CoreConnectionPNames.CONNECTION_TIMEOUT
) fixed the problem for me.Also, read the Apache docs carefully: http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/params/CoreConnectionPNames.html#CONNECTION_TIMEOUT
Note the bit that says
I hope that saves someone else all the head scratching I went through. That will teach me not to read the documentation thoroughly!