我使用以下代码从 URL 下载文件..
while(status==Status.DOWNLOADING){
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.connect();
int size=conn.getContentLength();
BufferedInputStream bin=new BufferedInputStream(conn.getInputStream());
byte[] buffer=new byte[1024];
int read=bin.read(buffer);
if(read==-1)
break;
downloaded+=read;
}
对于某些 URL 的 read() 方法,在读取下载的大小(内容长度)之前返回 -1。
有人可以建议我,这段代码发生了什么吗?
请提供您的建议..
最佳答案
不保证网络服务器在 http header 中提供内容长度。因此你不应该依赖它。只需像这样读取流:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = bin.read(buf)) > 0) {
bos.write(buf, 0, len);
}
byte[] data = bos.toByteArray();
关于java - HttpInputStream read() 方法失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6404525/