自动关闭HttpURLConnection与JAVA中的数据库连接(使用try-with-resourse)相同

时间:2018-11-19 06:00:00

标签: java httpurlconnection

自动关闭HttpURLConnection(与使用资源尝试的数据库连接相同) 在这里我正在寻找关闭HttpURLConnection,而没有手动关闭ex:urlConnection.disconnect();在最后一个区块

1 个答案:

答案 0 :(得分:0)

这并不完全相同,但是您可以为Autocloseable写一个包装器类。

class AutocloseWrapper<T> implements Autocloseable {
    T wrapped;
    Consumer<T> closeMethod;
    public AutocloseWrapper(T wrapped, Consumer<T> closeMethod) {
        this.wrapped = wrapped; this.closeMethod = closeMethod;
    }
    public void close() {
        closeMethod.accept(wrapped);
    }
}

然后用

private void yourMethod() {
    HttpUrlConnection connection = createConnection();
    try (AutocloseWrapper wrapper = new AutocloseWrapper(connection, HttpUrlConnection::disconnect)) {
        // do your stuff with the connection
    }
    // connection.disconnect() will have been called here
}