【问题标题】:Getting filename and extension from friendly url in java从java中的友好url获取文件名和扩展名
【发布时间】: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-DispositionContent-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 包含要下载的文件的名称 + 其扩展名。

【问题讨论】:

    标签: java http url


    【解决方案1】:

    看看 curl 的输出:

    curl -s -D - 'http://urlblacklist.com/cgi-bin/commercialdownload.pl?type=download&file=bigblacklist' -o /dev/null
    

    您将看到以下响应:

    HTTP/1.1 200 OK
    Date: Sun, 06 Sep 2015 00:55:51 GMT
    Server: Apache/2.4.10 (Debian)
    Content-disposition: attachement; filename=bigblacklist.tar.gz
    Content-length: 22840787
    Content-Type: application/octet-stream
    

    我猜这就是浏览器获取文件名和扩展名的方式:

    Content-disposition: attachement; filename=bigblacklist.tar.gz
    

    或者用 Java 来做:

        URL obj = new URL("http://urlblacklist.com/cgi-bin/commercialdownload.pl?type=download&file=bigblacklist");
        URLConnection conn = obj.openConnection();
        String disposition = conn.getHeaderField("Content-disposition");
        System.out.println(disposition);
    

    注意:服务器似乎在尝试多次后阻止了您的 IP,因此如果您今天已经尝试了多次,请务必从“干净”IP 尝试此操作。

    【讨论】:

    • 感谢您的回复!实际问题在于 IP 阻塞。这就是为什么我决定使用代理,现在它对我有用!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多