Java HttpInputStream读取()方法失败

Java HttpInputStream读取()方法失败,java,inputstream,urlconnection,Java,Inputstream,Urlconnection,我使用以下代码从URL下载文件 while(status==Status.DOWNLOADING){ HttpURLConnection conn=(HttpURLConnection)url.openConnection(); conn.connect(); int size=conn.getContentLength(); BufferedInputStream bin=new BufferedInputStream(conn.getInputStream()); byt

我使用以下代码从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

有人能告诉我,这个代码怎么了


请提供您的建议。

不能保证Web服务器在http头中提供内容长度。因此,你不应该依赖它。只需像这样阅读流:

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();

不能保证Web服务器在http头中提供内容长度。因此,你不应该依赖它。只需像这样阅读流:

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();