Connection Timeout In Java HTTPClient, RestTemplate and URLConnection

Connection timeout is the time for which an HTTP client or Socket client waits, if the server doesn’t respond in that time or not found then the client closes the connection. HTTP also uses sockets internally. Connection timeout is different from the Connection Request timeout or connection read timeout.

In many situations, the client doesn’t want to wait for a long time in that case a connection time out or Request connection timeout or both can be set.

Here are an example of the most used Java HTTP clients.

HttpURLConnection Timeout Example

Here is an example of setting connection time out and connection read time out.

try {
	final URL url = new URL("");

	final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

	// Sets a specified timeout value, in milliseconds, to be used when opening a
	// communications link to the resource reference by this URLConnection. If the
	// timeout expires before the connection can be established,
	// a is raised. A timeout of zero is interpreted
	// as an infinite timeout.
	// Here 5 second time out is set
	urlConn.setConnectTimeout(5 * 1000);
	urlConn.setReadTimeout(5 * 1000);
			"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv: Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
} catch (final Exception e) {

Apache HttpClient Timeout example

Here is an example of setting Connection time out and Request Connection time out. Not Connection Read timeout is the same as Request connection timeout.

try {
	final int timeout = 5000;// 5 seconds
	final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout)
	final HttpClientBuilder builder = HttpClientBuilder.create();
	final HttpClient client =;

	final HttpGet request = new HttpGet(""); // GET Request

	final HttpResponse response = client.execute(request);
} catch (final Exception e) {

Spring RestTemplate Timeout Example

Here is an example of the RestTemplate timeouts. It will set 5 seconds connection timeout and 5 seconds of reading time out.

RestTemplate template =  new RestTemplate();
HttpComponentsClientHttpRequestFactory rf =
	    (HttpComponentsClientHttpRequestFactory) template.getRequestFactory();
	rf.setReadTimeout(5 * 1000);
	rf.setConnectTimeout(5 * 1000);

You can define it as given below in Spring config

public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) 
    return restTemplateBuilder

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.