在不关闭 InputStream 的情况下关闭 HttpURLConnection?

Close HttpURLConnection without closing InputStream?

我有一个方法可以打开 HttpURLConnection,然后 returns 来自对调用者的响应的 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 没有关闭有多糟糕?最终会被关闭吗?或者我应该在一段时间后实施某种机制来关闭它吗?或者 copy/clone InputStream 和 return 副本,这样我就可以关闭 HttpURLConnection?

您不想让连接保持打开状态。这将存在资源泄漏的风险。我建议创建一个自定义 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 传递给构造函数和 return 自定义输入流:

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