繁体   English   中英

从Java中的友好URL获取文件名和扩展名

[英]Getting filename and extension from friendly url in java

我正在编写一个小型Java程序,用于从Internet下载黑名单。
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"为: "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包含要下载的文件的名称及其扩展名。

看一下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尝试此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM