在寫網絡爬蟲的時候,需要根據鏈接來獲取文件類型,將內容正確存儲。之前我都是根據鏈接的后綴來判斷的,比如:
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));