catch是否加载了url

ljo96ir5  于 2021-07-09  发布在  Java
关注(0)|答案(3)|浏览(284)

很难说出这里要问什么。这个问题模棱两可,含糊不清,不完整,过于宽泛,或者是修辞性的,不能以现在的形式得到合理的回答。有关澄清此问题以便重新打开的帮助,请访问帮助中心。
7年前关门了。
我有一个简单的应用程序,可以在网络视图中显示网页。因为其中一个网址还没有在线,我想祝酒词,说它是不是在线,当它是,它只是加载该网址。
有人知道怎么做吗?
提前谢谢。

7xllpg7q

7xllpg7q1#

你可以扩展你自己的异常

public class Exception404 extends Exception {
}

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

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

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

5cg8jx4n

5cg8jx4n2#

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

ukqbszuj3#

好吧,看看这个。。。

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

}catch(异常e){

// Your execution will reach here once the site can't be reached

 Toast.makeText(Your_Activity.this, "Site still not online",duration).show();

}

相关问题