开发者

How to handle problem with Network Connectivity in Java

I have a simple java c开发者_如何学Pythonode 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??


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜