2011-04-27 28 views
12

我需要對用戶插入的url的內容類型(如果是圖像,音頻或視頻)進行篩選。我有這樣的代碼:獲取內容類型的最快方法

URL url = new URL(urlname); 
URLConnection connection = url.openConnection(); 
connection.connect(); 
String contentType = connection.getContentType(); 

我得到的內容類型,但問題是,它似乎有必要下載整個文件,以檢查它的內容類型。所以當文件相當大時,它會持續太久的時間。我需要在Google App Engine應用程序中使用它,以便將請求限制在30秒內。

是否有任何其他方式來獲取URL的內容類型而無需下載文件(因此可以更快地完成)?

+0

只是一個想法:如何抓拍前n個字節,然後關閉連接?在大多數情況下,應該可以在文件的開始處猜測內容類型。但我不在這裏。 – pintxo 2011-04-27 09:55:48

+0

@pintxo爲什麼你會這樣做,如果你可以讀取頭部參數:'Content-Type',而不是通過'GET'獲得整個請求,你只需執行'HEAD'而不是 – 2015-05-07 12:40:42

回答

20

如果「其他」端支持它,您可以使用HEAD HTTP方法嗎?

+0

謝謝你給了我一個好主意 – Javi 2011-04-27 09:54:28

+0

請注意重定向,我的遠程內容檢查面臨同樣的問題。看看我的代碼,我在哪裏檢查。 – 2015-05-07 12:39:07

29

感謝DaveHowes回答和周圍的Googling有關如何獲取HEAD我得到了它這樣:

URL url = new URL(urlname); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
connection.setRequestMethod("HEAD"); 
connection.connect(); 
String contentType = connection.getContentType(); 
+7

'你是否真的在用Google搜索'如何獲取HEAD'? – 2016-06-14 18:30:43

9

注意重定向的,我面臨同樣的問題與我的遠程內容的檢查。
這裏是我的解決辦法:

/** 
* Http HEAD Method to get URL content type 
* 
* @param urlString 
* @return content type 
* @throws IOException 
*/ 
public static String getContentType(String urlString) throws IOException{ 
    URL url = new URL(urlString); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
    connection.setRequestMethod("HEAD"); 
    if (isRedirect(connection.getResponseCode())) { 
     String newUrl = connection.getHeaderField("Location"); // get redirect url from "location" header field 
     logger.warn("Original request URL: '{}' redirected to: '{}'", urlString, newUrl); 
     return getContentType(newUrl); 
    } 
    String contentType = connection.getContentType(); 
    return contentType; 
} 

/** 
* Check status code for redirects 
* 
* @param statusCode 
* @return true if matched redirect group 
*/ 
protected static boolean isRedirect(int statusCode) { 
    if (statusCode != HttpURLConnection.HTTP_OK) { 
     if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP 
      || statusCode == HttpURLConnection.HTTP_MOVED_PERM 
       || statusCode == HttpURLConnection.HTTP_SEE_OTHER) { 
      return true; 
     } 
    } 
    return false; 
} 

你也可以把一些櫃檯maxRedirectCount避免無限重定向循環 - 但是這裏沒有覆蓋。這只是一個靈感。

+1

不錯。爲什麼你需要問: if(statusCode!= HttpURLConnection.HTTP_OK){ – Dejell 2016-04-17 18:37:42

+0

@Dejell它的處理重定向 – 2016-04-19 08:03:20