毕业设计网
JSP,JAVA | python | nodejs | android,安卓 | PHP | 微信小程序 |

Android基于http协议多线程断点续传程序

程序测试环境:Win7 + Eclipse + Android2.2以上模拟器     数据库:SQLite

程序功能:
  输入指定的网络文件地址,程序创建多个线程,同时对目标文件执行下载到sd卡中!下载的过程中监视总共下载的完成的字节数,然后通过和总的长度进行计算更新显示下载进度条!同时每个线程在进行数据下载的过程中,还采用SQLite数据库将各个线程的编号和已经下载的数据长度保存到了数据库中!这样即使手机断电了,当再次运行程序,重新读取数据库中保存的文件下载进度信息,从而实现了断点续传功能,数据的请求采用http协议,需要服务器支持http断点下载功能!
cn.company.net.download.DownloadThread类实现http下载协议代码如下:
@Override
 public void run() {
  if(downLength < block){//未下载完成
   try {
    HttpURLConnection http = (HttpURLConnection) downUrl.openConnection();
    http.setConnectTimeout(5 * 1000);
    http.setRequestMethod("GET");
    http.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.m****cel, application/vnd.ms-powerpoint, application/msword, */*");
    http.setRequestProperty("Accept-Language", "zh-CN");
    http.setRequestProperty("Referer", downUrl.toString());
    http.setRequestProperty("Charset", "UTF-8");
    int startPos = block * (threadId - 1) + downLength;//开始位置
    int endPos = block * threadId -1;//结束位置
    http.setRequestProperty("Range", "bytes=" + startPos + "-"+ endPos);//设置获取实体数据的范围
    http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
    http.setRequestProperty("Connection", "Keep-Alive");
   
    InputStream inStream = http.getInputStream();
    byte[] buffer = new byte[1024];
    int offset = 0;
    print("Thread " + this.threadId + " start download from position "+ startPos);
    RandomAccessFile threadfile = new RandomAccessFile(this.saveFile, "rwd");
    threadfile.seek(startPos);
    while ((offset = inStream.read(buffer, 0, 1024)) != -1) {
     threadfile.write(buffer, 0, offset);
     downLength += offset;
     downloader.update(this.threadId, downLength);
     downloader.append(offset);
    }
    threadfile.close();
    inStream.close();
    print("Thread " + this.threadId + " download finish");
    this.finish = true;
   } catch (Exception e) {
    this.downLength = -1;
    print("Thread "+ this.threadId+ ":"+ e);
   }
  }
 }
android图片 

以上是一部分介绍,如需要完整的资料或者如不符合您的要求,请联系技术人员qq:242219979咨询

上一篇:Android基于安卓手机个人理财系统
下一篇:Android文件上传断点续传程序


版权所有 毕业设计网联系qq:242219979 © 2007-2022