如何在Java中处理网络连接问题

如何在Java中处理网络连接问题,java,android,Java,Android,我有一个简单的java代码,可以从输入url获取html文本: 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

我有一个简单的java代码,可以从输入url获取html文本:

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){}
我正在android项目中使用此代码。现在,当没有互联网连接时,问题就来了。应用程序只是暂停,然后出现错误

是否有某种方法可以在某个固定超时后中断此操作,或者甚至在引发异常后返回某些特定字符串。你能告诉我怎么做吗???

试试这个:

    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();
     }
一个空的catch块在自找麻烦。

试试以下方法:

    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();
     }

一个空的catch块在自找麻烦。

我不知道URL的默认超时是多少,快速查看一下javadocs似乎没有发现任何东西。因此,请尝试直接使用
HttpURLConnection
。这允许您设置超时值:

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(); 
}

您还可以设置读取超时,以及指定行为重新重定向和其他一些事情。

我不知道URL的默认超时是什么,快速查看一下javadocs似乎不会透露任何信息。因此,请尝试直接使用
HttpURLConnection
。这允许您设置超时值:

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(); 
}

您还可以设置读取超时,以及指定行为重新重定向和其他一些事项。

我认为除了超时之外,在请求之前检查互联网可用性也是明智的:

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);
    }
}

更新:有关超时,请参阅kuester2000的回复。

我认为除了超时之外,在请求之前检查互联网可用性也是明智之举:

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);
    }
}

更新:有关超时的信息,请参阅kuester2000的回复。

只是使用
流的一般提示
s在不再需要时始终关闭它们。我只是想把它贴出来,因为似乎大多数人在他们的示例中都没有注意到这一点。

只是一个关于使用
流的一般提示。
s在不再需要它们时总是关闭它们。我只是想把它贴出来,因为大多数人在他们的例子中似乎没有注意到这一点。

谢谢大家,顺便说一句,Richard,你的答案简单而有效。它解决了我所有的问题。我可以同时完成这两项任务,检查字符串的null值和timeout就可以了。非常感谢。谢谢大家,顺便说一句,理查德。你的回答简单而有效。它解决了我所有的问题。我可以同时完成这两项任务,检查字符串的null值和timeout就可以了。非常感谢。我会处理好的。谢谢你的提示,我会处理好的。谢谢你的提示。当你测试它时,它是连接的,而不是当你阅读的时候,情况如何?这种事是徒劳的。无论如何,你必须处理例外情况,没有必要重复两次。通常,查看资源是否可用的方法是尝试将其用于您需要使用它的目的。其他任何事情基本上都是要求计算机预测未来。那么,当你测试它时,它是连接的,而不是当你进行阅读时,情况又如何呢?这种事是徒劳的。无论如何,你必须处理例外情况,没有必要重复两次。通常,查看资源是否可用的方法是尝试将其用于您需要使用它的目的。其他任何事情基本上都是要求计算机预测未来。