[英]Close HttpURLConnection without closing InputStream?
I have a method that opens a HttpURLConnection
and then returns the InputStream
from the response to the caller:我有一个方法可以打开一个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.
}
My problem is I cannot close the HttpURLConnection
in this method as that would close the underlying InputStream
, which the caller of this method is responsible for closing.我的问题是我无法在此方法中关闭HttpURLConnection
,因为这将关闭底层InputStream
,此方法的调用者负责关闭。 I have no control over the callers.我无法控制来电者。
How bad is it that the HttpUrlConnection
is not closed? HttpUrlConnection
没有关闭有多糟糕? Will it eventually be closed?最终会关闭吗? Or should I implement some mechanism to close it after a period of time has elapsed?或者我应该在一段时间后实施某种机制来关闭它? Or maybe copy/clone the InputStream
and return the copy, which would allow me to close the HttpURLConnection
?或者也许复制/克隆InputStream
并返回副本,这将允许我关闭HttpURLConnection
?
You do not want to leave the connection open.您不想让连接保持打开状态。 That will present the risk of a resource leak.这将带来资源泄漏的风险。 I would recommend creating a custom InputStream
implementation that automatically closes the connection when the stream is closed:我建议创建一个自定义InputStream
实现,当 stream 关闭时自动关闭连接:
public class HttpURLConnectionInputStream extends InputStream {
private HttpURLConnection connection;
private InputStream stream;
public HttpURLConnectionInputStream(HttpURLConnection connection) throws IOException {
this.connection = connection;
this.stream = connection.getInputStream();
}
@Override
public int read() throws IOException {
return stream.read();
}
@Override
public void close() throws IOException {
connection.disconnect();
}
}
Then just pass your HttpURLConnection
to the constructor and return the custom input stream:然后只需将您的HttpURLConnection
传递给构造函数并返回自定义输入 stream:
public InputStream get() throws IOException {
final URL url = new URL("http://example.com");
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestMethod("GET");
httpUrlConnection.connect();
return new HttpURLConnectionInputStream(httpUrlConnection);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.