I am working on an Android app that needs to read a line from a web page right when it starts. I am doing this with the following code:
try{
URL url = new URL("http://www.example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
line = reader.readLine();
}
catch(Exception e){
e.printStackTrace();
}
It is working fine, but sometimes the connection or the server are slow, and the app freezes or crashes.
I want to put a timeout of 5 seconds, and should it reach that timeout I want to show a toast to the user saying the network is busy, asking him to try again later.
I tried the HttpURLConnection setConnectTimeout() method but it didn't work.
Any clues how I can achieve this? Thanks forehand.