判断URL是否能够访问JS和java两种方法

来源:互联网 发布:sql学生成绩管理系统 编辑:程序博客网 时间:2024/06/03 19:41

JS:此方法在IE下面不行

function getURL(url){

     var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

     xmlhttp.open("GET",url,false);  xmlhttp.send();

     if(xmlhttp.readyState==4){

            if(xmlhttp.Status!=200){ alert("URL地址不存在!"); }else{window.location.href=url; }

     }   

}

 java:

  1. /** 
  2.       * 功能:检测当前URL是否可连接或是否有效, 
  3.       * 描述:最多连接网络 3 次, 如果 3 次都不成功,视为该地址不可用 
  4.       * @param  urlStr 指定URL网络地址 
  5.       * @return URL 
  6.       */  
  7.      public synchronized String isConnect(String urlStr) {  
  8.          int counts = 0;  
  9.          retu = "";  
  10.          if (urlStr == null || urlStr.length() <= 0) {                         
  11.              return null;                   
  12.          }  
  13.          while (counts < StaticConstant.REQUEST_COUNT) {  
  14.              long start = 0;  
  15.              try {  
  16.                  url = new URL(urlStr);  
  17.                  start = System.currentTimeMillis();  
  18.                  con = (HttpURLConnection) url.openConnection();  
  19.                  state = con.getResponseCode();  
  20.                  log.info("请求断开的URL一次需要:"+(System.currentTimeMillis()-start)+"毫秒");  
  21.                  if (state == 200) {  
  22.                      retu = "ok";  
  23.                      log.info(urlStr+"--可用");  
  24.                  }  
  25.                  break;  
  26.              }catch (Exception ex) {  
  27.                  counts++;   
  28.                  log.info("请求断开的URL一次需要:"+(System.currentTimeMillis()-start)+"毫秒");  
  29.                  log.info("连接第 "+counts+" 次,"+urlStr+"--不可用");  
  30.                  continue;  
  31.              }  
  32.          }  
  33.          return retu;  
  34.      }


原创粉丝点击