【发布时间】:2015-09-06 00:52:05
【问题描述】:
我正在编写一个用于从 Internet 下载黑名单的小型 Java 程序。
URL 可以有两种类型:
1) 直接链接,例如:http://www.shallalist.de/Downloads/shallalist.tar.gz
这里绝对没问题,我们可以使用一些库,例如:apache.commons.io.FilenameUtils; 或者简单地查找最后出现的"/" 和"."
2) “友好的网址”,类似于:http://urlblacklist.com/cgi-bin/commercialdownload.pl?type=download&file=bigblacklist
这里没有明确的文件名和扩展名,但如果我使用我的浏览器或 Internet 下载管理器 (IDM),文件名+扩展名将是:"bigblacklist.tar.gz"
如何在 java 中解决这个问题并从“友好”的 URL 中获取文件名和扩展名?
PS:我知道 Content-Disposition 和 Content-Type 字段,但 urlblacklist 链接的响应标头是:
Transfer-Encoding : [chunked]
Keep-Alive : [timeout=5, max=100]
null : [HTTP/1.1 200 OK]
Server : [Apache/2.4.10 (Debian)]
Connection : [Keep-Alive]
Date : [Sat, 05 Sep 2015 23:51:35 GMT]
Content-Type : [ application/octet-stream]
正如我们所见,.gzip (.gz) 没有任何关联。如何使用java处理它?
Web 浏览器和下载管理器如何识别正确的名称和扩展名?
===============更新=====================
感谢@eugenioy,问题得到了解决。真正的麻烦在于我多次下载尝试的 IP 阻塞,这就是我决定使用代理的原因。现在它看起来像(对于这两种类型的 URL):
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIP, port));
HttpURLConnection httpConn = (HttpURLConnection) new URL(downloadFrom).openConnection(proxy);
String disposition = httpConn.getHeaderField("Content-Disposition");
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename");
if (index > 0) {
fullFileName = disposition.substring(disposition.lastIndexOf("=") + 1, disposition.length() );
}
} else {
// extracts file name from URL
fullFileName = downloadFrom.substring(downloadFrom.lastIndexOf("/") + 1, downloadFrom.length());
}
现在fullFileName 包含要下载的文件的名称 + 其扩展名。
【问题讨论】: