2010-11-17 44 views
1

我有一个简单的Java代码,从输入Url获取HTML文本:如何与网络连接处理问题在Java中

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项目。现在问题出现在没有互联网连接的情况下。该应用程序只是暂停,然后给出错误。

是否有某种方法可以在某些固定的超时后打破这种情况,甚至在抛出异常后返回某些特定的字符串。你能告诉我怎么做吗?

回答

1

我不知道URL的默认超时值是什么,快速查看javadocs似乎没有发现任何东西。所以请尝试直接使用HttpURLConnection而不是http://download.oracle.com/javase/1.5.0/docs/api/java/net/HttpURLConnection.html。这使您可以设置超时值:

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

您还可以设置读取超时,以及,以及指定的行为再重定向和其他一些东西。

+0

Thankyou所有,顺便说一句理查德你的答案简单而高效。它解决了我所有的问题。我可以同时执行这两项任务,检查字符串是否为空值,超时值是否可以作为待遇。 非常感谢。 – Rizwan 2010-11-17 23:21:46

+0

@Rizwan - np :) – 2010-11-18 09:48:11

2

试试这个:

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块是自找麻烦。

1

我想除了超时也可能是还聪明的请求权之前检查Internet可用性:

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:对于超时看到一个优秀的kuester2000的回复here

+1

当你测试它的时候它被连接了,但是当你阅读时没有连接的情况怎么样?这种事情是徒劳的。无论如何,你必须处理特殊情况,没有意义的是两次。一般来说,查看资源是否可用的方法是尝试将其用于您需要的目的。其他任何事情基本上都是要求电脑预测未来。 – EJP 2010-11-18 08:19:24

0

只要在与Stream合作时使用的一般技巧总是在不再需要时关闭它们。我只是想将其发布,因为似乎大多数人没有在他们的例子中关心它。

+0

当然会照顾这一点。谢谢你的提示。 – Rizwan 2010-11-17 23:27:44