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

时间:2015-09-06 00:52:06

标签: java http url

我正在编写一个小型java程序,用于从Internet下载黑名单。
URL可以有两种类型:
1)直接链接,例如:http://www.shallalist.de/Downloads/shallalist.tar.gz
这里绝对没有问题,我们可以使用一些库,例如:apache.commons.io.FilenameUtils;或只是查找"/""."的最后一次出现
2)“frienly url”,类似于:http://urlblacklist.com/cgi-bin/commercialdownload.pl?type=download&file=bigblacklist
这里没有明确的文件名和扩展名,但如果我使用我的浏览器或Internet下载管理器(IDM),文件名+扩展名将是:"bigblacklist.tar.gz"
如何在java中解决这个问题并从“友好”URL获取文件名和扩展名?

P.S:我知道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包含要下载的文件的名称及其扩展名。

1 个答案:

答案 0 :(得分: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,因此请务必尝试使用" clean" IP,如果你今天已经多次尝试过。