[英]AutoClose HttpURLConnection same as DB Connection(using try-with-resourse) in JAVA
Auto closing HttpURLConnection (same as DB Connection using try-with-resourse) here i am looking for closing HttpURLConnection,without closing manually ex:urlConnection.disconnect(); 自动关闭HttpURLConnection(与使用尝试资源的数据库连接相同)在这里,我正在寻找关闭HttpURLConnection,而无需手动关闭ex:urlConnection.disconnect(); in finally block 在最后块
It's not exactly the same, but you can write a wrapper class for Autocloseable
that kind of does it for you. 这并不完全相同,但是您可以为Autocloseable
编写包装类, 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);
}
}
And you'd call that with 你会用
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.