用getContentLength()方法获得网络文件的大小出错

susuifeng 2010-05-20 08:44:22
import java.io.IOException;
import java.net.URL;
class test {
public static void main( String[ ] args ) throws Exception {
test t=new test();

t.getLength("http://224.cachefile30.rayfile.com/e5cb/zh-cn/download/3ef8e0cb98a945dec0f96c0101cd4bc8/preview.mp3");
System.out.println();
t.getLength("http://www.python.org/ftp/python/2.5/python-2.5.msi");
System.out.println();
}
static void getLength(String str)throws Exception {
URL url = new URL(str);
int size = url.openConnection( ).getContentLength( );

System.out.printf( "%s is only %.1f MB in size. ", url, size / Math.pow( 2, 20 ) );
}
}


上述代码的运行结果是,
http://224.cachefile30.rayfile.com/e5cb/zh-cn/download/3ef8e0cb98a945dec0f96c0101cd4bc8/preview.mp3     is only     -0.0 MB in size. 
http://www.python.org/ftp/python/2.5/python-2.5.msi is only 10.2 MB in size.


为什么第一个没法获得正确的文件大小?为什么这个文件的大小是未知的? 是服务器不支持获取吗?
...全文
1425 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
susuifeng 2010-05-22
  • 打赏
  • 举报
回复
getContentLength()方法是通过获取网络资源的http响应头里的"Content-Length"来实现的,也就是说,如果这个资源摆明了不让你下载,根本就不给你提供获得大小的机会.....算是HttpURLConnection实现下载的局限吧......

将上面不能获得文件长度的地址复制到浏览器地址栏,会自动转到rayfile的下载页,最后点击右键,另存为,就能华丽地下载了...............用程序怎么实现呢?
susuifeng 2010-05-20
  • 打赏
  • 举报
回复
"http://224.cachefile19.rayfile.com/47a7/zh-cn/download/5eaf73476d825e64ea261abd79d044ea/preview.wma"

还有这个地址,也不能获得大小.........
susuifeng 2010-05-20
  • 打赏
  • 举报
回复
莫非是因为要及时关闭连接?

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧