Android HttpURLConnection断点下载(单线程)
HttpCilent跟HttpURLConnection是安卓原生的用来实现http请求的类:
Android6.0之后取消了HttpClient,不支持跟新,今天小编使用的是HttpURLConnection:
直接上代码:
URLurl=null;
BufferedInputStreambin=null;
HttpURLConnectionhttpURLConnection=null;
Contextcontext;
try{
//你要下载文件的路径
StringurlPath="MyUrlPath"
longfileSize=file.length;
//获取开始下载位置
longstartOffset=getFileLength(context);
url=newURL(urlPath);
//获取HttpURLConnection对象
httpURLConnection=(HttpURLConnection)url.openConnection();
//设置请求方式
httpURLConnection.setRequestMethod("GET");
//设置字符编码,这个字符编码表示为头500个字节:Range:bytes=0-499
表示第二个500字节:Range:bytes=500-999
表示最后500个字节:Range:bytes=-500
表示500字节以后的范围:Range:bytes=500-
第一个和最后一个字节:Range:bytes=0-0,-1
同时指定几个范围:Range:bytes=500-600,601-999
httpURLConnection.setRequestProperty("Range","bytes="+startOffset+"-");
//打开到此URL引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
if(httpURLConnection.getResponseCode()==206){
//ifstartOffset==0的时候,你就要把你的文件大小保存起来
//获取文件的大小httpURLConnection.getContentLength();
//当你第一次下载的时候,也就是你的起始位置是0的时候,这就是这个文件的总大小,如果bytes=xx的范围大于0,那么你获取的值就是你的文件总大小-bytes
//获取文件输出流
bin=newBufferedInputStream(httpURLConnection.getInputStream());
//这个是你要保存在那个目录的位置
Filefolder=newFile(DOWNLOADDIR);
//如果文件夹不存在则新建一个文件夹
if(!folder.exists()){
folder.mkdirs();
}
//随机访问文件,可以指定断点续传的起始位置
//flieAbsolutePath是你具体的文件路径
RandomAccessFilerandomAccessFile=newRandomAccessFile(flieAbsolutePath,"rwd");
//rwd跟r跟w的区别是rwd:边读编写边下载r读w写
randomAccessFile.seek(startOffset);
byte[]buffer=newbyte[2048];
intlen;
//isStop可以用来实现暂停功能
while((len=bin.read(buffer))!=-1&&!isStop){
randomAccessFile.write(buffer,0,len);
startOffset+=len;
//刷新下载进度
Messagemsg=newMessage();
msg.what=(int)((startOffset*100)/fileSize);
//使用handler发送消息刷新UI
handler.sendMessage(msg);
//保存下载的位置到SharedPreferences,下次下载的时候拿值写入设置字符编码
saveFileLength(context,startOffset);
}
}
}catch(MalformedURLExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(url!=null){
url=null;
}
if(bin!=null){
try{
bin.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(httpURLConnection!=null){
httpURLConnection.disconnect();
}
}
returnnull;
}
/**
*保存文件长度
*@paramcontext
*@paramfileLength
*/
privatestaticvoidsaveFileLength(Contextcontext,LongfileLength){
SharedPreferencessp=context.getSharedPreferences("My_SP",Context.MODE_PRIVATE);
SharedPreferences.Editoreditor=sp.edit();
editor.putLong("File_startOffset",fileLength);
editor.commit();
}
/**
*获取文件长度
*@paramcontext
*@return
*/
privatestaticLonggetFileLength(Contextcontext){
SharedPreferencessp=context.getSharedPreferences("My_SP",Context.MODE_PRIVATE);
returnsp.getLong("File_startOffset",0);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。