edit_note帖子
109
stars积分
1,066
event加入
2011-07-28
怀旧国机
[教程]Java获取URL链接的文件类型
schedule发表于 2012-08-08 14:31:00
visibility查看 232
chat_bubble回复 3
#1 楼主
在写网络爬虫的时候,需要根据链接来获取文件类型,将内容正确存储。之前我都是根据链接的后缀来判断的,比如:
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类型。
第一个是:
1. public static String guessContentTypeFromName(Stringname)
这个方法根据URL文件部分的后缀名来判断类型,跟之前我的方法一样。这个不能解决上面那个问题。
第二个是:
1. public static String guessContentTypeFromStream(InputStream in)
这个方法是根据流的前面几个字节来判断类型,这个就不需要文件后缀名了,完全可以解决上面那个问题。
测试代码如下:
1. BufferedInputStream bis = null ;
2. HttpURLConnection urlconnection = null ;
3. URL url = null ;
4. url = new URL(strUrl);
5. urlconnection = (HttpURLConnection) url.openConnection();
6. urlconnection.connect();
7. bis = new BufferedInputStream(urlconnection.getInputStream());
8. System.out.println( “file type:“ +HttpURLConnection.guessContentTypeFromStream(bis));
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类型。
第一个是:
1. public static String guessContentTypeFromName(Stringname)
这个方法根据URL文件部分的后缀名来判断类型,跟之前我的方法一样。这个不能解决上面那个问题。
第二个是:
1. public static String guessContentTypeFromStream(InputStream in)
这个方法是根据流的前面几个字节来判断类型,这个就不需要文件后缀名了,完全可以解决上面那个问题。
测试代码如下:
1. BufferedInputStream bis = null ;
2. HttpURLConnection urlconnection = null ;
3. URL url = null ;
4. url = new URL(strUrl);
5. urlconnection = (HttpURLConnection) url.openConnection();
6. urlconnection.connect();
7. bis = new BufferedInputStream(urlconnection.getInputStream());
8. System.out.println( “file type:“ +HttpURLConnection.guessContentTypeFromStream(bis));
全部回复 (3)
2012-08-08 14:34:00
沙发
你好厉害
2012-08-08 14:43:00
板凳
【Hacker〉顶帖组为你顶帖
加入【Hacker〉顶帖组吧!
2012-09-15 20:03:00
地板
????
登录 后才能回复
flag举报帖子