Should I close HttpUrlConnection and InputStream in this case? Only closing the connection will close the stream also? 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
HttpURLConnectionobject, it MAY also close anyInputStreamorOutputStreamthat it has opened.HttpURLConnection.disconnect()method description:You can read more here.
In turn,
Socket.close()method description:You can read more here.
But pay attention that "disconnecting"
HttpURLConnectiondoesn’t mandatory close theSocket. It have been already discussed quite well in that thread:On the other hand, in the official oracle tutorials they suggest to close
InputStreamexplicitly in order to be sure that resources don’t leak.