相关文章推荐
帅气的山羊  ·  eax, ebx, ecx, edx, ...·  1 月前    · 
留胡子的柠檬  ·  Configuration ...·  2 年前    · 
刚分手的花生  ·  sourcetreeapp.com ...·  2 年前    · 

关闭HttpURLConnection而不关闭InputStream?

1 人关注

我有一个方法,打开一个 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?

java
sockets
http
inputstream
httpurlconnection
rmf
rmf
发布于 2021-06-08
1 个回答
Cardinal System
Cardinal System
发布于 2021-06-08
已采纳
0 人赞同

你不希望让连接处于开放状态。这将带来资源泄漏的风险。我建议创建一个自定义的 InputStream 实现,当流被关闭时自动关闭连接。

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();

然后只需将你的HttpURLConnection 传递给构造函数并返回自定义输入流。

public InputStream get() throws IOException {
    final URL url = new URL("http://example.com");
    HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();