2017-05-25 42 views
1

試圖獲得一個簡單的java程序運行。每當我嘗試這段代碼,雖然我在線程「main」中得到異常java.lang.IllegalStateException:正在進行連接Java 404 Checker連接進行中

這是代碼。

public class Checker404 
{ 

public static int getResponseCode(String urlString) throws MalformedURLException, IOException 
{ 
    URL u = new URL(urlString); 
    HttpURLConnection huc = (HttpURLConnection) u.openConnection(); 
    huc.connect(); 

    huc.setRequestMethod("HEAD"); 
    huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)"); 
    huc.disconnect(); 
    return 1;  
} 

public static void main(String[] args) throws Exception 
{ 
    final String URL = "http://www.asda.com"; 
    Checker404.getResponseCode(URL); 

} 
} 

我試圖改變周圍的huc.connect請求財產和requestMethod之前,它只會編譯,但不能做任何事情。但是,當它是這樣的我得到連接進行中的錯誤。任何的建議都受歡迎。我對編程有點新,所以請原諒我的不一致之處。

回答

0

如果這是你的所有代碼,那麼正確的結果是它「什麼都不做」。它將在URL上執行Checker404,得到1的結果,並且對結果無效。 huc.connect()應該在huc.disconnect()之前。

+0

謝謝。我結束了它的工作。我也剛剛刪除了返回,將int更改爲void並做了system.out.print(huc.getResponseCode,它給了我網頁的狀態。) 謝謝! – Christian

1

huc.connect()應該在huc.disconnect()之前。