android下载url,Android:从URL下载

博主在尝试从网上下载一个4MB的文件时,发现代码仅下载了13KB便停止。问题可能出在服务器缺少Content-Length头,导致getContentLength()返回-1。代码中使用了一个1024字节的缓冲区读取并写入文件,同时有进度更新的日志显示。博主寻求帮助理解并解决这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm trying an example download code online and I found out that it downloads to about 13KB and then exits. The file is 4 MB. Can anybody help me explain why this is? Here's the code. Thanks.

//this is the total size of the file

int totalSize = urlConnection.getContentLength();

//variable to store total downloaded bytes

int downloadedSize = 0;

//create a buffer...

byte[] buffer = new byte[1024];

int bufferLength = 0; //used to store a temporary size of the buffer

//now, read through the input buffer and write the contents to the file

while ( (bufferLength = inputStream.read(buffer)) > 0 ) {

//add the data in the buffer to the file in the file output stream (the file on the sd card

fileOutput.write(buffer, 0, bufferLength);

//add up the size so we know how much is downloaded

downloadedSize += bufferLength;

//this is where you would do something to report the prgress, like this maybe

//updateProgress(downloadedSize, totalSize);

Log.w( "DOWNLOAD" , "progress " + downloadedSize + " / " + totalSize);

I noticed that the totalSize is -1 when calling getContentLength()...probably because of the missing content length from the header.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值