posts - 72, comments - 66, trackbacks - 0, articles - 0

java 探测网络资源是否可用

Posted on 2008-07-28 15:16 Fingki.li 阅读(3171) 评论(4)  编辑  收藏 所属分类: About development
要用java检测网络资源是否可用,我们可以采用以下两种方法:
一种方法是调用ping命令,
如:
      Process   process=   Runtime.getRuntime().exec("ping   192.168.0.5");  
      InputStreamReader   return   =   new   InputStreamReader(process.getInputStream());  
      LineNumberReader   returnData   =   new   LineNumberReader   (return);    
   
      String   line="";  
      while((line=returnData.readLine())!=null){  
          System.out.println(line);  
      }
通用对返回数据进行分析,来探测网络资源的可用性;
这种方法有一个缺点:就是许多网络资源是不允许被ping的,从而针对这类资源无法探测。
另一种方法是使用URL,
如:
                URL url = new URL("http://localhost");  
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
                int state = connection.getResponseCode();  
                String responseContent = connection.getResponseMessage();
通过分析ResponseCode来探测网络资源的可用性。
另外,当指定的网络资源走SSL时,即用https协议时,需要加入可信证书到trust.keystore.
通常情况下,我的用的是jre的keystore:cacerts,如jdk6下的路径为:jdk1.6.0_05/jre/lib/security/cacerts
我们需要把指定资源的数字证书导入到信任库 cacerts.
可以使用keytool工具:keytool -import -alias localhost -file localhost.cer -keystore cacerts
如果我们不想使用jre的keystore,我们可以建立自己的keystore,
        System.setProperty("javax.net.ssl.trustStore", "/home/liqingfeng/workspace/Test/mystore/localhost.keystore");
        System.setProperty("javax.net.ssl.trustStorePassword","changeit");
用keytool命令把localhost的证书导入到指定的localhost.keystore中。这样我们就可以用URL来探测SSL网络资源的可用性了。

这里必须注意的是指定网络资源的证书的CN,必须与资源访问地址一致,否则会报错。
以下是常见异常:
当keystore中没有指定资源的证书时:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
当指定资源证书的CN与资源访问地址不匹配时:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching localhost found





Feedback

# re: java 探测网络资源是否可用  回复  更多评论   

2008-07-28 23:59 by 隔叶黄莺
new URL("http://localhost");

这只是对 http 协议的,其他诸多的 ftp(21) smtp(25) pop3(110) snmp(161,152) ssh(22),不一而足,应用的,如 oracle(1521) mysql(3066),更是数不胜数,逐一去试,好像就是端口描述工具干的事情。

要是ping(icmp) 协议能通就能断定网络通的,就是那些禁ping(对icmp消息不回送)的就不是很好办。

还有一种情况,如果是要经过代码才能到达的,是否应考虑呢?

# re: java 探测网络资源是否可用  回复  更多评论   

2008-08-04 14:21 by Fingki.li
我这里只提到了http/https protocol相关的,至于其它协议,我没有去尝试,但感觉用socket可以解决吧。
对于ping这种方法我是很不赞同的,除非是内部测试,因为很多情况下对外公开的网络都是禁ping的。
至于说“如果是要经过代码才能到达的”,对于http/https protocol来讲,无非就是一些servlet,访问相应的servlet是否可用就可以了。

# re: java 探测网络资源是否可用[未登录]  回复  更多评论   

2008-10-13 18:07 by XYZ
指定资源证书的CN与资源访问地址不匹配这是指什么??
能否详细讲一下,我现在遇到了javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching localhost found这个异常。

# re: java 探测网络资源是否可用[未登录]  回复  更多评论   

2008-10-20 16:05 by Fingki.li
@XYZ
证书有个属性叫CN,一般我们申请证书时,它要与相应的资源相一致。
比如,为www.abc.com申请证书,这个证书的CN就为www.abc.com
用以表明这个证书是为它颁发的。
如果不一致就会报上面的异常。

只有注册用户登录后才能发表评论。


网站导航: