java和android文件下载断点续传概要.docx
《java和android文件下载断点续传概要.docx》由会员分享,可在线阅读,更多相关《java和android文件下载断点续传概要.docx(16页珍藏版)》请在冰豆网上搜索。
![java和android文件下载断点续传概要.docx](https://file1.bdocx.com/fileroot1/2023-5/24/d0106278-c5b2-4ed3-a6aa-7c62bce126e3/d0106278-c5b2-4ed3-a6aa-7c62bce126e31.gif)
java和android文件下载断点续传概要
java和android文件下载
packagecom.example.filetest;
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.RandomAccessFile;
import.HttpURLConnection;
import.MalformedURLException;
import.URL;
importjava.security.KeyManagementException;
importjava.security.KeyStoreException;
importjava.security.NoSuchAlgorithmException;
importjava.security.UnrecoverableKeyException;
/*importmons.httpclient.DefaultHttpMethodRetryHandler;
importmons.httpclient.cookie.CookiePolicy;
importmons.httpclient.methods.GetMethod;
importmons.httpclient.params.HttpMethodParams;*/
importorg.apache.http.Header;
importorg.apache.http.HttpException;
importorg.apache.http.HttpResponse;
importorg.apache.http.HttpStatus;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.conn.ClientConnectionManager;
importorg.apache.http.conn.scheme.PlainSocketFactory;
importorg.apache.http.conn.scheme.Scheme;
importorg.apache.http.conn.scheme.SchemeRegistry;
importorg.apache.http.conn.ssl.SSLSocketFactory;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
importorg.apache.http.message.BasicHeader;
importorg.apache.http.params.BasicHttpParams;
importorg.apache.http.params.HttpConnectionParams;
importandroid.content.Context;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
import.ConnectivityManager;
import.NetworkInfo;
importandroid.text.TextUtils;
importandroid.util.Log;
publicclassNetDownlodUtils{
publicinterfaceDownloadCallback{
voidonStart(longdownloaded,longfileSize);
voidonProgress(intprogress,longdowloaded,longfileSize);
voidOnFinished(booleancompleted,longfileSize,Stringremark);
}
privatefinalstaticintTIMEOUT_CONNECTION=15*1000;
privatefinalstaticintTIMEOUT_SOCKET=15*1000;
privatefinalstaticintRETRY_TIME=2;
publicstaticfinalStringUTF_8="UTF-8";
privatestaticfinalStringTAG="NetDownlodUtils";
/**
*下载文件,实现断点续传,添加range到header
*@paramurl
*@paramdestFile
*@return
*/
publicstaticFiledownloadBreakpointContinuingly(Stringurl,FiledestFile,DownloadCallbackcb){
RandomAccessFileraf=null;
InputStreaminput=null;
longfileSize=0;
StringerrorMsg=null;
try{
Log.d(TAG,"Startingdownloadfile:
"+destFile+",url:
"+url);
newFile(destFile.getParent()).mkdirs();
fileSize=getDownloadFileSize(url);
destFile.createNewFile();
raf=newRandomAccessFile(destFile,"rw");
longdownloaded=raf.length();
if(cb!
=null){
cb.onStart(downloaded,fileSize);
}
Log.d(TAG,"shoulddownloadrestfilesize:
"+(fileSize-downloaded));
HttpGetget=getHttpGet(url,raf.length(),-1);
HttpResponseresponse=getHttpClient().execute(get);
intcode=response.getStatusLine().getStatusCode();
Log.d(TAG,"downloadfilereturncode:
"+code);
if(code==HttpStatus.SC_PARTIAL_CONTENT){
raf.seek(destFile.length());
errorMsg="HttpStatus.SC_PARTIAL_CONTENT";
}elseif(code==HttpStatus.SC_NOT_FOUND){
errorMsg="HttpStatus.SC_NOT_FOUND";
returnnull;
}elseif(code!
=HttpStatus.SC_OK){
errorMsg="code!
=HttpStatus.SC_OK!
!
code="+code;
returnnull;
}
longrestFileSize=response.getEntity().getContentLength();
Log.d(TAG,"trydownloadrestfilesize="+restFileSize);
//TODO最好先检查存储空间,面的写数据失败
input=response.getEntity().getContent();
bytedata[]=newbyte[4096];
intcount;
while((count=input.read(data))!
=-1){
raf.write(data,0,count);
intprogress=fileSize==0?
0:
(int)(raf.length()*100/fileSize);
if(cb!
=null){
cb.onProgress(progress,raf.length(),fileSize);
}
}
}catch(Exceptione){
e.printStackTrace();
Log.w(TAG,e.toString());
}finally{
try{
input.close();
}catch(IOExceptione){
e.printStackTrace();
}
try{
raf.close();
}catch(IOExceptione){
e.printStackTrace();
}
if(cb!
=null){
cb.OnFinished(true,fileSize,errorMsg);
}
}
returndestFile;
}
/**
*实现断点续传,添加range到header
*注意点:
range区间不能指定end,否则在某些情况下(如阿里云服务器)不生效),不指定end绘制解把文件读完整
*@paramurl
*@paramstart
*@return
*/
protectedstaticHttpGetgetHttpGet(Stringurl,longstart,longend){
HttpGethttpGet=newHttpGet(url);
if(start>=0){
StringBufferrange=newStringBuffer("bytes="+start+"-");
if(end>start){
range.append(end);
}
HeaderheaderRange=newBasicHeader("Range",range.toString());
Log.d(TAG,"rangeheader:
"+headerRange);
httpGet.addHeader(headerRange);
}
returnhttpGet;
}
/**
*如果尚未知道文件的下载大小,则先主动获取一下
*/
privatestaticlonggetDownloadFileSize(Stringurl){
longfileSize=0;
try{
HttpGetget=getHttpGet(url,0,-1);
fileSize=getHttpClient().execute(get).getEntity().getContentLength();
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
returnfileSize;
}
publicstaticNetworkInfogetNetworkInfo(Contextcontext){
ConnectivityManagerconnectivityManager=(ConnectivityManager)context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfonetworkInfo=connectivityManager.getActiveNetworkInfo();
returnnetworkInfo;
}
publicstaticbooleanisNetConnected(Contextcontext){
if(context!
=null){
NetworkInfoni=getNetworkInfo(context);
returnni!
=null&&ni.isAvailable()&&ni.isConnected();
}
returnfalse;
}
/**
*getnettypename:
cmwap/cmnet/wifi/uniwap/uninet/ctnet/ctwap
*@paramcontext
*@return
*/
publicstaticStringgetNetWorkTypeName(Contextcontext){
StringnetworkType=null;
try{
NetworkInfonetworkInfo=getNetworkInfo(context);//NULL
if(networkInfo!
=null&&networkInfo.isAvailable()){
StringtypeName=networkInfo.getTypeName();//MOBILE/WIFI
if(!
"MOBILE".equalsIgnoreCase(typeName)){
networkType=typeName;
}else{
networkType=networkInfo.getExtraInfo();//cmwap/cmnet/wifi/uniwap/uninet
if(networkType==null){
networkType=typeName+"#[]";
}
}
}
}catch(Exceptione){
e.printStackTrace();
}
returnnetworkType;
}
publicstaticBitmapgetNetBitmap(Stringurl){
returndownloadNetBitmap(url);
}
publicstaticInputStreamdownloadNetStream(Stringurl){
InputStreaminput=null;
intretryTimes=0;
do{
try{
HttpURLConnectioncon=(HttpURLConnection)newURL(url).openConnection();
con.setDoInput(true);
con.connect();
input=con.getInputStream();
intmaxSize=con.getContentLength();
Log.i(TAG,"maxSize=="+maxSize);
returninput;
}catch(MalformedURLExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}
if(input==null){
retryTimes++;
if(retryTimestry{
Thread.sleep(1000);
Log.i(TAG,"downloadNetStreamretryTimes="+retryTimes);
}catch(InterruptedExceptione1){
}
continue;
}
}
}while(retryTimesreturninput;
}
publicstaticBitmapdownloadNetBitmap(Stringurl){
Bitmapbitmap=null;
InputStreaminStream=null;
try{
inStream=downloadNetStream(url);
if(inStream!
=null){
bitmap=BitmapFactory.decodeStream(inStream);
}
}catch(OutOfMemoryErrore3){
e3.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}finally{
if(inStream!
=null){
try{
inStream.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
returnbitmap;
}
publicstaticvoidsaveStreamToFiles(Contextcontext,InputStreamis,
StringfileName){
if(is==null)
return;
byte[]buffer=newbyte[1024];
intlen=-1;
try{
FileOutputStreambos=context.openFileOutput(fileName,
Context.MODE_PRIVATE);
while((len=is.read(buffer))!
=-1){
bos.write(buffer,0,len);
bos.flush();
}
if(bos!
=null){
bos.close();
}
is.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
publicstaticBitmapgetHttpBitmap(Stringurl){
HttpClienthttpClient=null;
HttpGethttpGet=null;
InputStreaminStream=null;
Bitmapbmp=null;
intretryTimes=0;
try{
do{
try{
httpClient=getHttpClient();
httpGet=getHttpGetMethod(url,null,null);
HttpResponseres=httpClient.execute(httpGet);
intstatusCode=res.getStatusLine().getStatusCode();
if(statusCode!
=HttpStatus.SC_OK){
thrownewException("errorstatusCode="+statusCode);
}
inStream=res.getEntity().getContent();
bmp=BitmapFactory.decodeStream(inStream);
inStream.close();
break;
}catch(OutOfMemoryErrore3){
e3.printStackTrace();
}catch(HttpExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}
if(bmp==null){
retryTimes++;
if(retryTimestry{
Thread.sleep(1000);
Log.w(TAG,"downloadBitmapretryTimes="+retryTimes);
}catch(InterruptedExceptione3){
}
continue;
}
}
}while(retryTimes}catch(Exceptione){
e.printStackTrace();
}finally{
httpClient=null;
}