1. 程式人生 > >從檔案/檔案流的頭位元組中得到mime資訊

從檔案/檔案流的頭位元組中得到mime資訊

在寫網路爬蟲的時候,需要根據連結來獲取檔案型別,將內容正確儲存。之前我都是根據連結的字尾來判斷的,比如:

http://img12.360buyimg.com/da/20120330/88_31_ZySDre.jpg

這個連結指向的檔案就是個jpg檔案。但是後來發現有諸如

http://jprice.360buyimg.com/getSkuPriceImgService.action?skuId=1850001109&origin=1&webSite=1&type=1的連結,這招就不靈了。後來谷歌百度了一下也沒發現解決辦法。後來機緣巧合在Java Network Programming上找到了一個辦法:

URLConnection class provides two static methods to help programs figure out the MIME type of some data; you can use these if the content type just isn't available or if you have reason to believe that the content type you're given isn't correct。

就是說URLConnection提供了兩種方法可以猜測(根據實測結果,這個猜測是相當的準)資料的MIME型別。

  第一個是:

public static String guessContentTypeFromName(String name)

這個方法根據URL檔案部分的字尾名來判斷型別,跟之前我的方法一樣。這個不能解決上面那個問題。
第二個是:
public static String guessContentTypeFromStream(InputStream in)
這個方法是根據流的前面幾個位元組來判斷型別,這個就不需要檔案字尾名了,完全可以解決上面那個問題。

測試程式碼如下:
BufferedInputStream bis = null; HttpURLConnection urlconnection =
null; URL url = null;         url = new URL(strUrl); urlconnection = (HttpURLConnection) url.openConnection(); urlconnection.connect(); bis = new BufferedInputStream(urlconnection.getInputStream()); System.out.println("file type:"+HttpURLConnection.guessContentTypeFromStream(bis));