首页 文章

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

提问于
浏览
0

以下构造方法应将URL从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);
}

Questions:

  • 不应该首先解析 InputStream 然后关闭 HttpURLConnection

  • 在我尝试 get 之前 httpcon 之前不应该有 httpcon.connect() 吗?

1 回答

  • 1

    首先不应该解析InputStream然后关闭HttpURLConnection吗?

    是的,或者说关闭 InputStream.

    在我尝试从httpcon获取内容之前,不应该有http on.connect()吗?

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

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

相关问题