gpt4 book ai didi

java - 来自 HttpURLConnection 的输入流 : When to disconnect?

转载 作者:行者123 更新时间:2023-12-01 11:03:35 26 4
gpt4 key购买 nike

以下构造方法应将 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 吗?
  • 在我尝试从 httpcon 获取某些内容之前,不应该有一个 httpcon.connect() 吗?

最佳答案

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?

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

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

关于java - 来自 HttpURLConnection 的输入流 : When to disconnect?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33145919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com