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。什么是获得状态的正确解决方案

4

1 回答 1

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;
}
于 2012-10-03T13:33:21.350 回答