Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HTTP Client Request with defined timeout

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> 
like image 770
Maxim Veksler Avatar asked Jun 08 '10 18:06

Maxim Veksler


People also ask

How do I set timeout in HttpClient?

The default value is 100,000 milliseconds (100 seconds). To set an infinite timeout, set the property value to InfiniteTimeSpan. A Domain Name System (DNS) query may take up to 15 seconds to return or time out.

How do I set HTTP timeout in Java?

The fluent, builder API introduced in 4.3 provides the right way to set timeouts at a high level: int timeout = 5; RequestConfig config = RequestConfig. custom() . setConnectTimeout(timeout * 1000) .


2 Answers

If you are using Http Client version 4.3 and above you should be using this:

RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30 * 1000).build(); HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); 
like image 114
Thunder Avatar answered Oct 06 '22 01:10

Thunder


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;  ...      // set the connection timeout value to 30 seconds (30000 milliseconds)     final HttpParams httpParams = new BasicHttpParams();     HttpConnectionParams.setConnectionTimeout(httpParams, 30000);     client = new DefaultHttpClient(httpParams); 
like image 29
laz Avatar answered Oct 06 '22 01:10

laz