Showing posts with label setConnectTimeout. Show all posts
Showing posts with label setConnectTimeout. Show all posts

Wednesday, September 7, 2016

HttpURLConnection setConnectTimeout issues

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Give it a 4 seconds delay before deciding that it's a dead connection
connection.setConnectTimeout(10000);
connection.setRequestMethod("HEAD"); // Don't ask for content
connection.setAllowUserInteraction(false);
connection.connect(); 



Problem here is, application can hung for more than 10 sec even after configuring the timeout for connection.

How that can happen?

connection.setConnectTimeout() is only for configuring timeout to accept the connection, but after accepting the request server might take a long time to respond to you due to various issues at the server end. 

As per the doc - “timeout for opening a communications link to the resource referenced by this URLConnection”.

This kind of things will lead to application hung if you’re waiting for the response.


To resolve this - we should also set the connection.setReadTimeout(5000). 

As per doc - “timeout when reading from Input stream when a connection is established to a resource.”