From 8289e6a8da47db744f00b200a6d2e3f57acb1180 Mon Sep 17 00:00:00 2001 From: Looly Date: Thu, 7 May 2020 17:37:02 +0800 Subject: [PATCH] fix code --- CHANGELOG.md | 2 ++ .../java/cn/hutool/cache/impl/TimedCache.java | 2 +- .../java/cn/hutool/core/util/URLUtil.java | 28 +++++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5633ce1cf..d58197505 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,11 @@ ## 5.3.4 (2020-05-06) ### 新特性 +* 【core 】 增加URLUtil.getContentLength方法(issue#I1GB1Z@Gitee) ### Bug修复 * 【extra 】 修复Ftp设置超时问题 +* 【extra 】 修复TreeUtil根据id查找子节点时的NPE问题(pr#120@Gitee) ------------------------------------------------------------------------------------------------------------- diff --git a/hutool-cache/src/main/java/cn/hutool/cache/impl/TimedCache.java b/hutool-cache/src/main/java/cn/hutool/cache/impl/TimedCache.java index 03add0533..292ea326f 100644 --- a/hutool-cache/src/main/java/cn/hutool/cache/impl/TimedCache.java +++ b/hutool-cache/src/main/java/cn/hutool/cache/impl/TimedCache.java @@ -28,7 +28,7 @@ public class TimedCache extends AbstractCache { * @param timeout 超时(过期)时长,单位毫秒 */ public TimedCache(long timeout) { - this(timeout, new HashMap>()); + this(timeout, new HashMap<>()); } /** diff --git a/hutool-core/src/main/java/cn/hutool/core/util/URLUtil.java b/hutool-core/src/main/java/cn/hutool/core/util/URLUtil.java index 8a75e508a..62359ef8a 100644 --- a/hutool-core/src/main/java/cn/hutool/core/util/URLUtil.java +++ b/hutool-core/src/main/java/cn/hutool/core/util/URLUtil.java @@ -15,11 +15,13 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; +import java.net.URLConnection; import java.net.URLStreamHandler; import java.nio.charset.Charset; import java.util.Map; @@ -738,4 +740,30 @@ public class URLUtil { public static String buildQuery(Map paramMap, Charset charset) { return UrlQuery.of(paramMap).build(charset); } + + /** + * 获取指定URL对应资源的内容长度,对于Http,其长度使用Content-Length头决定。 + * + * @param url URL + * @return 内容长度,未知返回-1 + * @throws IORuntimeException IO异常 + * @since 5.3.4 + */ + public static long getContentLength(URL url) throws IORuntimeException{ + if(null == url){ + return -1; + } + + URLConnection conn = null; + try { + conn = url.openConnection(); + return conn.getContentLengthLong(); + } catch (IOException e) { + throw new IORuntimeException(e); + } finally { + if (conn instanceof HttpURLConnection) { + ((HttpURLConnection)conn).disconnect(); + } + } + } } \ No newline at end of file