views:

410

answers:

2

Hello,

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>
+1  A: 

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.

try {

   HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
   con.setRequestMethod("HEAD");
   con.setConnectTimeout(5000); //set timeout to 5 seconds
   return (con.getResponseCode() == HttpURLConnection.HTTP_OK);

} catch (java.net.SocketTimeoutException e) {
   return false;
} catch (java.io.IOException e) {
   return false;
}
dbyrne
This will not affect the timeout for Apache HTTP Client.
laz
Never claimed it did ;)
dbyrne
A: 
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

...

    final HttpParams httpParams = new BasicHttpParams();
    final HttpClient HttpConnectionParams.setConnectionTimeout(httpParams, 1);
    client = new DefaultHttpClient(httpParams);
laz
What does this do? A timeout of what does it set? Please see http://stackoverflow.com/questions/3000767/apache-httpclient-coreconnectionpnames-connection-timeout-does-nothing
Maxim Veksler