Posted on 2008-07-28 15:16
Fingki.li 閱讀(3200)
評論(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
我這里只提到了http/https protocol相關的,至于其它協議,我沒有去嘗試,但感覺用socket可以解決吧。
對于ping這種方法我是很不贊同的,除非是內部測試,因為很多情況下對外公開的網絡都是禁ping的。
至于說“如果是要經過代碼才能到達的”,對于http/https protocol來講,無非就是一些servlet,訪問相應的servlet是否可用就可以了。
# re: java 探測網絡資源是否可用[未登錄] 回復 更多評論
2008-10-13 18:07 by
指定資源證書的CN與資源訪問地址不匹配這是指什么??
能否詳細講一下,我現在遇到了javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching localhost found這個異常。
# re: java 探測網絡資源是否可用[未登錄] 回復 更多評論
2008-10-20 16:05 by
@XYZ
證書有個屬性叫CN,一般我們申請證書時,它要與相應的資源相一致。
比如,為www.abc.com申請證書,這個證書的CN就為www.abc.com
用以表明這個證書是為它頒發的。
如果不一致就會報上面的異常。