簡體   English   中英

來自服務器的響應代碼

[英]Response Code From Server

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通。 什么是獲得狀態的正確解決方案

您可以使用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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM