[英]InputStream from HttpURLConnection: When to disconnect?
The following constructor method should read an XML from an URL into a XML Document
object. 以下构造函数方法应将URL中的XML读入XML Document
对象。 While it already works, I still doubt it is correct. 尽管它已经可以工作,但我仍然怀疑它是正确的。
// 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
and then close the HttpURLConnection
? 不应该先解析InputStream
然后关闭HttpURLConnection
吗? httpcon.connect()
before I try to get
something from httpcon
? 在尝试从httpcon
get
之前,应该没有httpcon.connect()
吗? Shouldn't one first parse the InputStream and then close the HttpURLConnection? 一个人不应该首先解析InputStream然后关闭HttpURLConnection吗?
Yes, or rather close the InputStream.
是的,或者关闭InputStream.
Shouldn't there be a http on.connect() before I try to get something from httpcon? 在尝试从httpcon获取内容之前,不应该有一个http on.connect()吗?
No. It's implicit in getting the input stream. 不。它在获取输入流中是隐式的。
The code you posted is incorrect and should not work. 您发布的代码不正确,因此不起作用。 The input stream should be read before the disconnect. 断开连接之前,应先读取输入流。 Actually the disconnect is only necessary if you want o prevent connection pooling. 实际上,仅当您希望防止连接池时才需要断开连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.