【问题标题】:InputStream from HttpURLConnection: When to disconnect?来自 HttpURLConnection 的 InputStream:何时断开连接?
【发布时间】:2015-10-15 10:20:26
【问题描述】:

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

问题:

  • 不应该先解析InputStream然后关闭HttpURLConnection吗?
  • 在我尝试get 来自httpcon 的东西之前不应该有httpcon.connect() 吗?

【问题讨论】:

    标签: java inputstream httpurlconnection


    【解决方案1】:

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

    是的,或者关闭InputStream.

    在我尝试从 httpcon 获取一些东西之前不应该有一个 http on.connect() 吗?

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

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

    【讨论】:

      猜你喜欢
      • 2013-02-27
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多