判斷URL是否能夠訪問JS和java兩種方法

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.      }


發佈了35 篇原創文章 · 獲贊 5 · 訪問量 34萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章