首页 > 解决方案 > AutoClose HttpURLConnection 与 JAVA 中的 DB 连接(使用 try-with-resource)相同

问题描述

自动关闭 HttpURLConnection(与使用 try-with-reourse 的 DB 连接相同)在这里我正在寻找关闭 HttpURLConnection,而不是手动关闭 ex:urlConnection.disconnect(); 在 finally 块中

标签: javahttpurlconnection

解决方案


它不完全一样,但你可以为你编写一个包装类来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
}

推荐阅读