开发者

HttpInputStream read() method failure

开发者 https://www.devze.com 2023-03-14 04:22 出处:网络
I use following code to download file from URL.. while(status==Status.DOWNLOADING){ HttpURLConnection conn=(HttpURLConnection)url.openConnection();

I use following code to download file from 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;
}

for some URL's read() method return -1 before reading upto size(content length) of download..

开发者_开发百科

can anybody suggest me, what's happening with this code..

pls provide your suggestion..


Its not guaranteed that a webserver provides a content length in the http header. Therfore you should not rely on it. Just read the stream like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消