簡體   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