android下载文件大小,Android使用HttpGet下载文件计算下载进度

HttpClient client = SSLSocketFactoryEx.getNewHttpClient();

client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);

client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

//get请求加入参数

String content =null;

StringBuilder sb =new StringBuilder();

sb.append(remoteUrl);

Iterator it =map.entrySet().iterator();

while (it.hasNext()) {

Map.Entry entry = (Map.Entry) it.next();

try {

sb.append("&").append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));

}catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

}

content = sb.toString();

HttpGet get =new HttpGet(content);

try {

HttpResponse response = client.execute(get);

int status = response.getStatusLine().getStatusCode();

if (200 == status) {

if (response.getEntity() ==null){

callback.onError("response error");

}

length = response.getEntity().getContentLength();

localInputStream = response.getEntity().getContent();

//在本地存储文件

File localFile =new File(localFilePath);

localFileOutputStream =new FileOutputStream(localFile);

int bufsize = CommonUtils.getDownloadBufSize(this.context);

byte[] arrayOfByte =new byte[bufsize];

while ((i = localInputStream.read(arrayOfByte)) != -1) {

rate += i;

if (length >0) {

int progress = (int) (rate *100L / length);  //下载进度

if (callback !=null) {

callback.onProgress(progress);   //可以在回调中进行进度条更新

}

}

localFileOutputStream.write(arrayOfByte, 0, i);

}

callback.onSuccess(null);

}else {

if (callback !=null) {

callback.onError(null);

}

}

//后边的资源释放,异常捕获都省略了 ,只展示部分代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值