I am trying to get some data from remote server. To achieve this I use HttpURLConnection. The problem is that sometimes the server after connection is established just hangs or what, doesn’t close connection, and I hang there. Also that hanged thread acquired the lock, so all all other threads are just sucking 😀
Code:
try {
URL url = new URL(urlString);
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = (HttpURLConnection) urlConnection;
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName(CharEncoding.UTF_8)));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
Last line is where we are hanging. I found method setConnectTimeout(timeout), but seems this is not the case because it is timeout before connection is established. What is common way to solve such situations?
assuming you meant timeout after the connection is established (likely during the read), how about something like this