java - AutoClose HttpURLConnection 与 JAVA 中的 DB 连接(使用 try-with-resource)相同
问题描述
自动关闭 HttpURLConnection(与使用 try-with-reourse 的 DB 连接相同)在这里我正在寻找关闭 HttpURLConnection,而不是手动关闭 ex:urlConnection.disconnect(); 在 finally 块中
解决方案
它不完全一样,但你可以为你编写一个包装类来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
}
推荐阅读
- ios - 延迟任务直到完成
- documentation - 是否可以重用 Doxygen 生成的文档并与新文档合并?
- html - 将全尺寸图像的大小和比例与 SVG 视图框匹配
- c++11 - cgo 不包括 CXXFLAGS
- mysql - 直接模式下的 Sqoop 错误
- c++ - 使用 std::hex 将十六进制转换为十进制
- python - python将“unicode”转换为列表
- php - Symfony4:将服务注入控制器__construct(构造函数)
- google-bigquery - BigQuery - UNION ALL 的类型不兼容? - 使我抓狂
- r - 在 R 的 geosphere 包中,为什么轴承不在 0-360 度?