2015-10-15 42 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些什么呢?

不。它隐含在获取输入流中。

您发布的代码不正确,应该不起作用。输入流应在断开之前读取。实际上,只有在您想要阻止连接池时才需要断开连接。

相关问题