Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7453
  • 博文数量: 4
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 10
  • 用 户 组: 普通用户
  • 注册时间: 2014-04-18 23:34
文章分类
文章存档

2015年(4)

我的朋友
最近访客

分类: Web开发

2015-03-18 08:28:43

最近因项目需求,需要针对一些URL地址进行检测是否可用,使用java.net 下的类来实现,主要用到了 URL和HttpURLConnection 二个类。使用了HttpURLConnection 中的 getResponseCode();方法,HttpURLConnection : 通常一个HttpURLConnection 的实例可以生成一个请求,它有个方法 getResponseCode();可以得到请求的响应状态,该方法返回一个 int 分别是 200 and 404 如无法从响应中识别任何代码则返回 -1,代码如下:

  1. /** 
  2. * 文件名称为:URLAvailability.java 
  3. * 文件功能简述: 描述一个URL地址是否有效 
  4. * @author Jason 
  5. * @time   2010-9-14  
  6.  
  7. */  
  8. public class URLAvailability {  
  9. private static URL url;  
  10. private static HttpURLConnection con;  
  11. private static int state = -1;  
  12.   
  13. /** 
  14.    * 功能:检测当前URL是否可连接或是否有效, 
  15.    * 描述:最多连接网络 5 次, 如果 5 次都不成功,视为该地址不可用 
  16.    * @param urlStr 指定URL网络地址 
  17.    * @return URL 
  18.    */  
  19. public synchronized URL isConnect(String urlStr) {  
  20.    int counts = 0;  
  21.    if (urlStr == null || urlStr.length() <= 0) {                         
  22.     return null;                   
  23.    }  
  24.    while (counts < 5) {  
  25.     try {  
  26.      url = new URL(urlStr);  
  27.      con = (HttpURLConnection) url.openConnection();  
  28.      state = con.getResponseCode();  
  29.      System.out.println(counts +"= "+state);  
  30.      if (state == 200) {  
  31.       System.out.println("URL可用!");  
  32.      }  
  33.      break;  
  34.     }catch (Exception ex) {  
  35.      counts++;   
  36.      System.out.println("URL不可用,连接第 "+counts+" 次");  
  37.      urlStr = null;  
  38.      continue;  
  39.     }  
  40.    }  
  41.    return url;  
  42. }  
  43. }  
超级OK
阅读(1391) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:开源爬虫软件汇总

给主人留下些什么吧!~~