2012-10-09 43 views
12

我試圖從一個web服務中獲得一堆pdf鏈接,我想給用戶每個鏈接的文件大小。如何從java中的URL計算文件大小

有沒有辦法完成這項任務?

謝謝

+0

恐怕你將不得不下載文件至少一次以得到確切的大小。 (您可能希望將來存儲,但如果服務器上的文件發生更改,數據將失效) – Nishant

+1

@Nishant這是不正確的。 'HTTP HEAD'請求會返回有關您執行'HTTP GET'請求時會得到的信息的信息,該請求應包含返回請求的大小。你當然可以做'HEAD'請求並解析響應。 – Thor84no

+1

啊,好的。很高興知道。謝謝@ Thor84no – Nishant

回答

22

使用HEAD請求,你可以做這樣的事情:

private static int getFileSize(URL url) { 
    URLConnection conn = null; 
    try { 
     conn = url.openConnection(); 
     if(conn instanceof HttpURLConnection) { 
      ((HttpURLConnection)conn).setRequestMethod("HEAD"); 
     } 
     conn.getInputStream(); 
     return conn.getContentLength(); 
    } catch (IOException e) { 
     throw new RuntimeException(e); 
    } finally { 
     if(conn instanceof HttpURLConnection) { 
      ((HttpURLConnection)conn).disconnect(); 
     } 
    } 
} 
+0

我得到了下面的異常:java.io.IOException:服務器返回的HTTP響應代碼:405的URL。我可以在瀏覽器中打開pdf鏈接。這是否意味着這個URL不會允許頭部請求? – javaMan

+1

你能分享你的請求URL嗎? – 2012-10-09 13:28:36

+0

我很抱歉...網址需要我的憑據。我無法分享它。 :( – javaMan

6

嘗試使用HTTP HEAD方法。它僅返回HTTP標頭。標題Content-Length應該包含您需要的信息。

2

您是否嘗試過使用URL連接上的getContentLength? 如果服務器響應一個有效的頭文件,你應該得到文件的大小。

但請注意,網絡服務器也可能會以大塊的形式返回文件。在這種情況下,IIRC內容長度方法將返回一個塊的大小(< = 1.4)或-1(> 1.4)。

3

HTTP響應有一個Content-Length頭,所以你可以查詢此值的URLConnection對象。

一旦URL連接已經打開,你可以嘗試這樣的事:

List values = urlConnection.getHeaderFields().get("content-Length") 
if (values != null && !values.isEmpty()) { 

    // getHeaderFields() returns a Map with key=(String) header 
    // name, value = List of String values for that header field. 
    // just use the first value here. 
    String sLength = (String) values.get(0); 

    if (sLength != null) { 
     //parse the length into an integer... 
     ... 
    } 
} 
0

你可以試試這個..

private long getContentLength(HttpURLConnection conn) { 
    String transferEncoding = conn.getHeaderField("Transfer-Encoding"); 
    if (transferEncoding == null || transferEncoding.equalsIgnoreCase("chunked")) { 
     return conn.getHeaderFieldInt("Content-Length", -1); 
    } else { 
     return -1; 
    } 
3

接受的答案是容易NullPointerException,不爲文件> 2GiB工作,幷包含對getInputStream()的不必要的調用。這裏的固定代碼:

public long getFileSize(URL url) { 
    HttpURLConnection conn = null; 
    try { 
    conn = (HttpURLConnection) url.openConnection(); 
    conn.setRequestMethod("HEAD"); 
    return conn.getContentLengthLong(); 
    } catch (IOException e) { 
    return -1; 
    // Or wrap into a (custom, if desired) RuntimeException so exceptions are propagated. 
    // throw new RuntimeException(e); 
    // Alternatively you can just propagate IOException, but, urgh. 
    } finally { 
    if (conn != null) { 
     conn.disconnect(); 
    } 
    } 
}