检测当前URL是否可连接或是否有效

/**

* 文件名称为:URLAvailability.java

* 文件功能简述:描述一个URL地址是否有效

* @author sky

* @time   2010-9-14

*

*/

public class URLAvailability {

private static URL url;

private static HttpURLConnection con;

private static int state = -1;

 

/**

   * 功能:检测当前URL是否可连接或是否有效,

   * 描述:最多连接网络 5 , 如果 5 次都不成功,视为该地址不可用

   * @param urlStr 指定URL网络地址

   * @return URL

   */

public synchronized URL isConnect(String urlStr) {

   int counts = 0;

   if (urlStr == null || urlStr.length() <= 0) {                      

    return null;                

   }

   while (counts < 5) {

    try {

     url = new URL(urlStr);

     con = (HttpURLConnection) url.openConnection();

     state = con.getResponseCode();

     System.out.println(counts +"= "+state);

     if (state == 200) {

      System.out.println("URL可用!");

     }

     break;

    }catch (Exception ex) {

     counts++;

     System.out.println("URL不可用,连接第 "+counts+" ");

     urlStr = null;

     continue;

    }

   }

   return url;

}

}

 

 

 

方法2:

static boolean exists(String URLName) 
{
  try 
  {
   HttpURLConnection.setFollowRedirects(false);
   HttpURLConnection con = (HttpURLConnection) new URL(URLName)
     .openConnection();
   con.setRequestMethod("HEAD");
   return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
  } 
  catch (Exception e)
  {
   e.printStackTrace();
   return false;
  }
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值