天天看點

curl 探測java網站_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