[英]Java close both Connection and InputStream with try statement
Should I close HttpUrlConnection and InputStream in this case?在这种情况下我应该关闭 HttpUrlConnection 和 InputStream 吗? Only closing the connection will close the stream also?只有关闭连接才会关闭 stream 吗? I feel that it's a bad practice but don't know exactly why.我觉得这是一种不好的做法,但不知道为什么。
Closing both:关闭两者:
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
try (AutoCloseable ac = con::disconnect) {
int responseCode = con.getResponseCode();
try (InputStream ins = responseCode >= 400 ? con.getErrorStream() : con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(ins))) {
// receive response
}
}
Closing Connection only:仅关闭连接:
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
try (AutoCloseable ac = con::disconnect) {
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(ins)))
// ins will close automatically when con closes?
// receive response
}
When you disconnect the HttpURLConnection
object, it MAY also close any InputStream
or OutputStream
that it has opened.当您断开HttpURLConnection
object 时,它可能还会关闭它已打开的任何InputStream
或OutputStream
。
HttpURLConnection.disconnect()
method description: HttpURLConnection.disconnect()
方法说明:
Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.如果此时持久连接处于空闲状态,则调用 disconnect() 方法可能会关闭底层套接字。
You can read more here .您可以在此处阅读更多内容。
In turn, Socket.close()
method description:反过来, Socket.close()
方法说明:
Closing this socket will also close the socket's InputStream and OutputStream.关闭此套接字也会关闭套接字的 InputStream 和 OutputStream。 If this socket has an associated channel then the channel is closed as well.如果此套接字有关联的通道,则该通道也会关闭。
You can read more here .您可以在此处阅读更多内容。
But pay attention that "disconnecting" HttpURLConnection
doesn't mandatory close the Socket
.但请注意,“断开连接” HttpURLConnection
并不强制关闭Socket
。 It have been already discussed quite well in that thread :已经在该线程中讨论得很好:
(When
keepAlive == true
) If client calledHttpURLConnection.getInputSteam().close()
, the later call toHttpURLConnection.disconnect()
will NOT close theSocket
. (当keepAlive == true
时)如果客户端调用HttpURLConnection.getInputSteam().close()
,稍后调用HttpURLConnection.disconnect()
将不会关闭Socket
。 ie TheSocket
is reused (cached) If client does not callclose()
, calldisconnect()
will close theInputStream
and close theSocket
.即Socket
被重用(缓存) 如果客户端不调用close()
,调用disconnect()
将关闭InputStream
并关闭Socket
。 So in order to reuse theSocket
, just callInputStream.close()
.所以为了重用Socket
,只需调用InputStream.close()
。 Do not callHttpURLConnection.disconnect()
.不要调用HttpURLConnection.disconnect()
。
On the other hand, in the official oracle tutorials they suggest to close InputStream
explicitly in order to be sure that resources don't leak.另一方面,在官方 oracle 教程中,他们建议明确关闭InputStream
以确保资源不会泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.