java 探测网络资源可用性的两个办法

要用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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值