1

I have a simple java code which gets html text from the input url:

try {
    URL url =  new URL("www.abc.com");
    // Get the  response
    BufferedReader rd = new BufferedReader(new  InputStreamReader(url.openStream()));

      while ((line  = rd.readLine()) != null) {
      String code = code + line;

     } catch (IOException  e){}

I am using this code in an android project. Now the problem comes when there is no internet connectivity. The application just halts and later gives error.

Is there some way to break this after some fixed timeout, or even return some specific string after an exception is thrown. Can you please tell me how to do that??

skaffman
  • 398,947
  • 96
  • 818
  • 769
Rizwan
  • 19
  • 1
  • 3

4 Answers4

2

Try this:

    try 
    {
        URL url =  new URL("www.abc.com");
        String newline = System.getProperty("line.separator");
        InputStream is = url.openStream();
        if (is != null)
        {
        BufferedReader rd = new BufferedReader(new  InputStreamReader(is));

        StringBuilder contents = new StringBuilder();
        while ((line  = rd.readLine()) != null) 
        {
            contents.append(line).append(newline);
        }           
        }
        else
        {
            System.out.println("input stream was null");            
        }
     } 
     catch (Exception  e)
     {
        e.printStackTrace();
     }

An empty catch block is asking for trouble.

duffymo
  • 305,152
  • 44
  • 369
  • 561
1

I don't know what the default timeout is for URL, and a quick look at the javadocs doesn't seem to reveal anything. So try using HttpURLConnection directly instead http://download.oracle.com/javase/1.5.0/docs/api/java/net/HttpURLConnection.html. This lets you set timeout values:

public static void main(String[] args) throws Exception {

    URL url = new URL("http://www.google.com");

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5000);    // 5 seconds
    conn.setRequestMethod("GET");       
    conn.connect();
    BufferedReader rd  = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    String line;
    while ((line = rd.readLine()) != null) {
        System.out.println(line);
    }
    conn.disconnect(); 
}

You can also set a read time out as well, as well as specify behaviour re redirects and a few other things.

Richard H
  • 38,037
  • 37
  • 111
  • 138
  • Thankyou All, btw Richard your answer was simple and efficient. It solved all my problem. I can do both the tasks, checking the string for null value and timeout works as a treat. thanks a lot. – Rizwan Nov 17 '10 at 23:21
1

I think in addition to timeouts it could be also smart to check the Internet availability right before the requesting:

public class ConnectivityHelper {

    public static boolean isAnyNetworkConnected(Context context) {
        return isWiFiNetworkConnected(context) || isMobileNetworkConnected(context);
    }

    public static boolean isWiFiNetworkConnected(Context context) {
        return getWiFiNetworkInfo(context).isConnected();
    }

    public static boolean isMobileNetworkConnected(Context context) {
        return getMobileNetworkInfo(context).isConnected();
    }

    private static ConnectivityManager getConnectivityManager(Context context) {
        return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    }
}

UPDATE: For timeouts see an excellent kuester2000's reply here.

Community
  • 1
  • 1
Vit Khudenko
  • 28,288
  • 10
  • 63
  • 91
  • 1
    What about the case where it was connected when you tested it but not when you did the reading? This kind of thing is futile. You have to handle the exceptional cases anyway, no point in going it all twice. In general the way to see if a resource is available is to try to use it for the purpose you need to use it for. Anything else is basically asking the computer to predict the future. – user207421 Nov 18 '10 at 08:19
0

Just a general tip on working with Streams always close them when they are no longer needed. I just wanted to post that up as it seems that most people didn't take care of it in their examples.

Octavian Helm
  • 39,405
  • 19
  • 98
  • 102