2012-10-03 58 views
0
public static boolean testConnection() { 
    try { 
     // TODO add your handling code here: 
     System.setProperty("http.proxyHost", "some proxy name"); 
     System.setProperty("http.proxyPort", "some port"); 
     URL a = new URL("http://" + Variables.serverName + ":" +   Variables.serverPort  + "/DeviceCloud"); 
     urlString = a.toExternalForm()+"/"; 
     System.out.println(urlString); 
     System.out.println("http://" + Variables.serverName + ":" + Variables.serverPort + "/DeviceCloud"); 
     URLConnection conn = a.openConnection(); 
     int respCode = ((HttpURLConnection) conn).getResponseCode(); 
     System.out.println(respCode); 
     if (respCode >= 500) { 
      return false; 
     } else { 
      return true; 
     } 
    } catch (Exception ex) { 
     return false; 
    } 
} 

它可以正常工作,如果服務器可達。但是,如果服務器不可達意味着它需要很長時間。 它沒有顯示任何輸出,但實際上服務器機器也從客戶端ping。 這可能是正確的解決方案要獲得狀態來自服務器的響應代碼

+0

ping命令並不意味着你可以打開一個HTTP連接到同一臺服務器。你能提供更多關於網絡的細節嗎?例如,您是否需要通過代理才能訪問主機? –

回答

1

您可以設置超時與setConnectTimeout()方法:

try { 
    HttpURLConnection httpconn = (HttpURLConnection) a.openConnection(); 
    httpconn.setConnectTimeout(10000); //10 seconds timeout 

    return (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK); 
} catch (SocketTimeoutException e) { 
    // You can get an output here if it timed out 
    return false; 
} 
相關問題