HttpUtils介绍

在了解了java和Android的多线程断点续传之后,再来介绍一个github上的开源库HttpUtils。

这个库本身有许多功能,这里只介绍下载相关的部分。库地址:https://github.com/wyouflf/xUtils

也可以直接到github上查看,上面的介绍也很详细。

下面直接上代码,主要部分都添加了注释。


package test.multdownload;

import java.io.File;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.fc.rssreader.R;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

public class HttpUtilsActivity extends Activity {

	public String url = "http://dldir1.qq.com/qqfile/qq/QQ7.2/14810/QQ7.2.exe";
//	public String url = "http://hiphotos.baidu.com/240728057/pic/item/6a50e38242aad8f60cf4d2b3.jpg";
	public String target = "sdcard/QQ7.2.exe";
	private ProgressBar pb;
	private TextView tv_progress;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_http_utils);
		pb = (ProgressBar) findViewById(R.id.pb);
		tv_progress = (TextView) findViewById(R.id.tv_progress);
	}

	public void click(View v) {
		HttpUtils http = new HttpUtils();
		HttpHandler handler = http.download(url,// 请求的地址
				target, // 下载文件保存的位置
				true, // 是否断点续传
				true,// 如果响应头可以拿到文件名,那么下载完成后自动重命名
				new RequestCallBack<File>() {

					//下载完成后调用此方法
					@Override
					public void onSuccess(ResponseInfo<File> arg0) {
						Toast.makeText(HttpUtilsActivity.this,
								arg0.result.getPath(), Toast.LENGTH_SHORT).show();
					}

					//下载失败调用此方法
					@Override
					public void onFailure(HttpException arg0, String arg1) {
						TextView tv = (TextView) findViewById(R.id.tv_status);
						tv.setText(arg1);
					}

					//用于刷新进度条
					@Override
					public void onLoading(long total, long current,
							boolean isUploading) {
						super.onLoading(total, current, isUploading);
						pb.setMax((int) total);
						pb.setProgress((int) current);
						tv_progress.setText(current * 100 / total + "%");
					}
				});
	}
}

不得不说现在的开源库真的很厉害,在自己写的下载程序中大约200行,而且功能相当简陋,而使用开源库实现的主体部分只有20行左右,功能完善使用方便而且没有bug。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值