2015-10-15 40 views
0

以下構造方法應將URL中的XML讀取到XML Document對象中。雖然它已經有效,但我仍然懷疑它是正確的。HttpURLConnection的InputStream:何時斷開?

// Basic constructor method without exception handling 
Feed(URL url) throws IOException, ParserConfigurationException, SAXException { 
    HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); 
    httpcon.addRequestProperty("User-Agent", "Some User-Agent"); 

    InputStream inStream = httpcon.getInputStream(); 

    httpcon.disconnect(); 

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = factory.newDocumentBuilder(); 
    doc = builder.parse(inStream); 
} 

問題:

  • 不應該一個第一解析InputStream,然後關閉HttpURLConnection
  • 不應該有httpcon.connect()之前我試圖get東西從httpcon

回答

1

不應該先解析InputStream然後關閉HttpURLConnection?

是的,或者更確切地說,關閉InputStream.

不應該有一個HTTP on.connect()之前,我試圖從httpcon些什麼呢?

不。它隱含在獲取輸入流中。

您發佈的代碼不正確,應該不起作用。輸入流應在斷開之前讀取。實際上,只有在您想要阻止連接池時才需要斷開連接。

相關問題