【问题标题】:Catch if url is loaded or not [closed]捕获 url 是否已加载[关闭]
【发布时间】:2012-08-24 15:32:17
【问题描述】:

我有一个在 WebView 中显示网页的简单应用程序。因为其中一个 url 还没有在线,所以我想祝酒,说它不在线,当它在线时,它只是加载 url。

有人知道如何做到这一点吗?

提前致谢。

【问题讨论】:

    标签: java android url webview


    【解决方案1】:

    打开一个 URLConnection,首先检查连接的响应码。如果这是 404,则表示该站点不存在。然后,您可以在那里做所有需要的站点缺失的东西。示例代码:

     try {
          Url url = new URL(someStringUrl);
          HttpURLConnection huc =  ( HttpURLConnection )  url.openConnection (); 
          if(huc.getResponseCode() == 404) {
               //Site doesnt exist, returned 404 error
          }
     } catch(Exception e) {
         e.printStackTrace();
     }
    

    【讨论】:

    • 感谢这几乎是答案,只是我使用字符串作为 url,所以它在“url.openconnection”上给出错误。
    • @user1534326 查看我的编辑
    • 它不会工作它只是给出一个空白页,我也尝试过祝酒。但是什么都没有。另外,当我尝试当前在线的页面时,它会给出一个空白页面
    【解决方案2】:

    你可以扩展你自己的异常,比如说

    public class Exception404 extends Exception {
    }
    

    然后捕获 2 个不同的异常:

    HttpURLConnection huc = null;
    
    try {
         Url url = new URL(someStringUrl);
         huc =  ( HttpURLConnection )  url.openConnection (); 
         if(huc.getResponseCode() == 404) 
            throw new Exception404();
    
         //...
         //...
         //...
    
     } catch(Exception404 e) { 
        e.printStackTrace();    
     } catch(Exception e) {
        e.printStackTrace();
     } finally {
        //close connection (saves battery life time)
        huc.disconnect();
     }
    

    或者你可以抛出相同的异常以相同的方式处理两个失败

    【讨论】:

    • 这和我的有什么不同?他们都有完全相同的结果,只是我的第一个发布......?如果有重大差异,请告诉我,我可能会遗漏一些东西
    • 是的,你是对的。但是,抛出一个异常,使代码更具可读性,因为你在 try 块的末尾处理了意外的结果。此外,也许需要抛出304 (unmodified since) 这将不会由以下函数处理,而是由调用此函数的函数处理。这比在成功/失败时传递布尔值更令人信服
    • 此外,我在 try 块的末尾关闭了连接,这将打开 android 设备的收音机(节省电池寿命)
    • 抛出异常仍然没有比 if 语句更漂亮或更具可读性,或者切换响应代码。但是,我确实忘记了断开连接;)
    【解决方案3】:

    看看这个...

    try {
          // Write your code to access the website here
    

    } 捕捉(异常 e){

    // Your execution will reach here once the site can't be reached
    
     Toast.makeText(Your_Activity.this, "Site still not online",duration).show();
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多