WEB如何判断某一URL是否可用

最近客户进行网络改造,在改造过程中会有应用服务器的IP发生改变,且在一段时间内各机构访问应用时地址会不同,有一些机构用192段的一个地址,有的用户就要用10段的一个地址,所以要在判断某一个请求时,一个URL不好使时,请求另一个URL,实验了几种方法。

1.使用JSP的方法,具体代码如下

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.net.URL" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.net.MalformedURLException" %>
<%@ page import="java.net.URLConnection" %>
<%@ page import="java.net.HttpURLConnection" %>
<%@ page import="java.io.IOException" %>
<%

       try {
          
            URL url = null;
            url = new URL("http://localhost:8080/test/temp1.jsp"); //将此处换成要测试是否连通的地址      
            HttpURLConnection   httpConnection   =   (HttpURLConnection)url.openConnection();
            httpConnection.getURL();
            int   responseCode=httpConnection.getResponseCode();
            System.out.println(responseCode);
            if(responseCode==200) {//如果响应码为200说明此地址是通的,则跳到该地址,
               response.sendRedirect("http://localhost:8080/test/temp1.jsp");
            }else{//否则跳到另外的地址
               response.sendRedirect("http://localhost:8080/test/temp2.jsp");
            }         
        } catch (MalformedURLException e) {          
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            response.sendRedirect("http://localhost:8080/test/temp1.jsp");
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
   
%>

2.使用javascript的方法

<%@ page contentType="text/html;charset=gb2312" language="java" %>
<html>
<script   language="javascript">  
  function   getURL(url)  
  {  
          var   xmlhttp;
          if (window.ActiveXObject) {
            xmlhttp   = new   ActiveXObject("Microsoft.XMLHTTP");  

           }
          else if (window.XMLHttpRequest) {
          xmlhttp   = new XMLHttpRequest();
          }  
          xmlhttp.open("GET",url,false);  
          xmlhttp.send();  
          if (xmlhttp.readyState==4)  
          {  
              if(xmlhttp.Status!=200)
              return false
              else  
              return true;
          }  
          return   false;  
  }  
  function targetRrl(){
    if(getURL("http://localhost:8080/test/temp1.jsp")==true)
    {
      window.location.href = "http://localhost:8080/test/temp1.jsp";

    }
    else{
     window.location.href = "http://localhost:8080/test/temp2.jsp";
    }
   }

  </script>  

<a οnclick="targetRrl();">链接</a>
</html>

注:此种方法有跨域访问的问题,所以必须修改浏览器中internet选项->安全->其它->通过域访问数据源 设为启动

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值