Looly 5 years ago
parent
commit
8289e6a8da

+ 2 - 0
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)
 
 -------------------------------------------------------------------------------------------------------------
 

+ 1 - 1
hutool-cache/src/main/java/cn/hutool/cache/impl/TimedCache.java

@@ -28,7 +28,7 @@ public class TimedCache<K, V> extends AbstractCache<K, V> {
 	 * @param timeout 超时(过期)时长,单位毫秒
 	 */
 	public TimedCache(long timeout) {
-		this(timeout, new HashMap<K, CacheObj<K, V>>());
+		this(timeout, new HashMap<>());
 	}
 
 	/**

+ 28 - 0
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<String, ?> 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();
+			}
+		}
+	}
 }