我有一个方法,打开一个
HttpURLConnection
,然后从响应中返回
InputStream
给调用者。
// Callers are responsible for closing the returned input stream
public InputStream get()
final URL url= new URL("http://example.com");
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestMethod("GET");
return httpUrlConnection.getInputStream();
// Don't close httpUrlConnection as that will close the returned input stream
// which the caller is responsible for closing.
我的问题是我不能在这个方法中关闭HttpURLConnection
,因为这将关闭底层的InputStream
,这个方法的调用者负责关闭。我对调用者没有控制权。
HttpUrlConnection
不被关闭的情况有多糟?它最终会被关闭吗?或者我应该实现一些机制,在一段时间后关闭它?或者复制/克隆InputStream
,并返回副本,这将使我能够关闭HttpURLConnection
?