2015-05-09 37 views
1

通過使用HtmlUnit瀏覽器,我得到HTTP標準響應代碼。根據響應代碼,我們正在決定服務器是否正在運行,以控制另一個線程。HtmlUnit - 服務器關閉後服務器(HTTP)狀態代碼不變

問題我們在這裏面臨的是,如果我們停止服務器,仍然會得到200(運行)響應代碼。

該網站的索引文件是一個純HTML文件,所以我們通過清除Cookie和Cache來嘗試。但即使在關閉服務器之後,我們仍然將響應代碼設置爲200。請指導,以找到一種方法來跟蹤時,正在運行的服務器成爲關/不迴應(HttpHostConnectException)

代碼的HtmlUnit:

while(alive) 
{ 
    try 
    { 
    c.clear(); 
    cm.clearCookies(); 
    SST = client.getPage("http://**ip**/DDT/").getWebResponse().getStatusCode(); 
    } 
    catch(HttpHostConnectException he) 
    { 
     isServerUP = false; 
    } 
    catch(FailingHttpStatusCodeException fhe) 
    { 
     isServerUP = false; 
    } 
    System.out.println(SST); 
    if(SST == 200) 
    { 
     isServerUP = true; 
    } 
    else 
    { 
     isServerUP = false; 
    } 
} 

回答

1

我無法重現,可能是Web客戶端是不同的配置。

隨着最新版本,下面的成功處理停止/啓動服務器:

try (WebClient webClient = new WebClient()) { 
    while (true) { 
     try { 
      int status = webClient.getPage("http://localhost/test.html").getWebResponse().getStatusCode(); 
      System.out.println(new Date() + " " + status); 
     } 
     catch(Exception e) { 
      System.out.println(e.getMessage()); 
     } 
     Thread.sleep(1000); 
    } 
} 
+0

謝謝艾哈邁德。我在循環中移動了聲明和關閉的WebClient,因此它現在正在工作。我不知道我們是否有更好的方法來解決這個問題。我已經提到了下面的代碼。 while(alive) { WebClient client = new Webclient //代碼 client.close(); } –

+1

你可以有while(true){try {new WebClient().. close()}},所以每次在循環中構建一個新的webclient並關閉()。你還有問題嗎?如果不是,請接受答案。 –

+0

謝謝艾哈邁德 –