来自 HttpURLConnection 的 InputStream:何时断开连接?

InputStream from HttpURLConnection: When to disconnect?

下面的构造方法应该将 XML 从 URL 读入 XML Document 对象。虽然它已经有效,但我仍然怀疑它是否正确。

// 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);
}

问题:

Shouldn't one first parse the InputStream and then close the HttpURLConnection?

是,或者更确切地说关闭 InputStream.

Shouldn't there be a http on.connect() before I try to get something from httpcon?

没有。它隐含在获取输入流中。

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