ImageVerifierCode 换一换
格式:DOCX , 页数:16 ,大小:18.36KB ,
资源ID:24071778      下载积分:3 金币
快捷下载
登录下载
邮箱/手机:
温馨提示:
快捷下载时,用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)。 如填写123,账号就是123,密码也是123。
特别说明:
请自助下载,系统不会自动发送文件的哦; 如果您已付费,想二次下载,请登录后访问:我的下载记录
支付方式: 支付宝    微信支付   
验证码:   换一换

加入VIP,免费下载
 

温馨提示:由于个人手机设置不同,如果发现不能下载,请复制以下地址【https://www.bdocx.com/down/24071778.html】到电脑端继续下载(重复下载不扣费)。

已注册用户请登录:
账号:
密码:
验证码:   换一换
  忘记密码?
三方登录: 微信登录   QQ登录  

下载须知

1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。
2: 试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。
3: 文件的所有权益归上传用户所有。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 本站仅提供交流平台,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

版权提示 | 免责声明

本文(java和android文件下载断点续传概要.docx)为本站会员(b****2)主动上传,冰豆网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知冰豆网(发送邮件至service@bdocx.com或直接QQ联系客服),我们立即给予删除!

java和android文件下载断点续传概要.docx

1、java和android文件下载 断点续传概要java和android文件下载package com.example.filetest;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.RandomAccessFile;import .HttpURLConnection;import .MalformedURLException;i

2、mport .URL;import java.security.KeyManagementException;import java.security.KeyStoreException;import java.security.NoSuchAlgorithmException;import java.security.UnrecoverableKeyException;/*import mons.httpclient.DefaultHttpMethodRetryHandler;import mons.httpclient.cookie.CookiePolicy;import mons.htt

3、pclient.methods.GetMethod;import mons.httpclient.params.HttpMethodParams;*/import org.apache.http.Header;import org.apache.http.HttpException;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.Http

4、Client;import org.apache.http.client.methods.HttpGet;import org.apache.http.conn.ClientConnectionManager;import org.apache.http.conn.scheme.PlainSocketFactory;import org.apache.http.conn.scheme.Scheme;import org.apache.http.conn.scheme.SchemeRegistry;import org.apache.http.conn.ssl.SSLSocketFactory;

5、import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;import org.apache.http.message.BasicHeader;import org.apache.http.params.BasicHttpParams;import org.apache.http.params.HttpConnectionParams;import android.content.Context;import an

6、droid.graphics.Bitmap;import android.graphics.BitmapFactory;import .ConnectivityManager;import .NetworkInfo;import android.text.TextUtils;import android.util.Log;public class NetDownlodUtils public interface DownloadCallback void onStart(long downloaded, long fileSize); void onProgress(int progress,

7、 long dowloaded, long fileSize); void OnFinished(boolean completed, long fileSize, String remark); private final static int TIMEOUT_CONNECTION = 15 * 1000; private final static int TIMEOUT_SOCKET = 15 * 1000; private final static int RETRY_TIME = 2; public static final String UTF_8 = UTF-8; private

8、static final String TAG = NetDownlodUtils; /* * 下载文件,实现断点续传,添加range到header * param url * param destFile * return */ public static File downloadBreakpointContinuingly(String url, File destFile, DownloadCallback cb) RandomAccessFile raf = null; InputStream input = null; long fileSize = 0; String error

9、Msg = null; try Log.d(TAG, Starting download file : + destFile + , url: + url); new File(destFile.getParent().mkdirs(); fileSize = getDownloadFileSize(url); destFile.createNewFile(); raf = new RandomAccessFile(destFile, rw); long downloaded = raf.length(); if(cb != null) cb.onStart(downloaded, fileS

10、ize); Log.d(TAG, should download rest filesize: + (fileSize - downloaded); HttpGet get = getHttpGet(url, raf.length(), -1); HttpResponse response = getHttpClient().execute(get); int code = response.getStatusLine().getStatusCode(); Log.d(TAG, download file return code: + code); if (code = HttpStatus.

11、SC_PARTIAL_CONTENT) raf.seek(destFile.length(); errorMsg = HttpStatus.SC_PARTIAL_CONTENT; else if (code = HttpStatus.SC_NOT_FOUND) errorMsg = HttpStatus.SC_NOT_FOUND; return null; else if (code != HttpStatus.SC_OK) errorMsg = code != HttpStatus.SC_OK ! code= + code; return null; long restFileSize =

12、response.getEntity().getContentLength(); Log.d(TAG, try download rest file size= + restFileSize); / TODO 最好先检查存储空间,面的写数据失败 input = response.getEntity().getContent(); byte data = new byte4096; int count; while (count = input.read(data) != -1) raf.write(data, 0, count); int progress = fileSize = 0 ? 0

13、 : (int) (raf.length() * 100 / fileSize); if(cb != null) cb.onProgress(progress, raf.length(), fileSize); catch (Exception e) e.printStackTrace(); Log.w(TAG, e.toString(); finally try input.close(); catch (IOException e) e.printStackTrace(); try raf.close(); catch (IOException e) e.printStackTrace()

14、; if(cb != null) cb.OnFinished(true, fileSize, errorMsg); return destFile; /* * 实现断点续传,添加range到header * 注意点: range区间不能指定end,否则在某些情况下(如阿里云服务器)不生效),不指定end绘制解把文件读完整 * param url * param start * return */ protected static HttpGet getHttpGet(String url, long start, long end) HttpGet httpGet = new HttpGet(

15、url); if(start = 0) StringBuffer range = new StringBuffer(bytes= + start + -); if(end start) range.append(end); Header headerRange = new BasicHeader(Range, range.toString(); Log.d(TAG, range header: + headerRange); httpGet.addHeader(headerRange); return httpGet; /* * 如果尚未知道文件的下载大小,则先主动获取一下 */ privat

16、e static long getDownloadFileSize(String url) long fileSize = 0; try HttpGet get = getHttpGet(url, 0, -1); fileSize = getHttpClient().execute(get).getEntity().getContentLength(); catch (ClientProtocolException e) e.printStackTrace(); catch (IOException e) e.printStackTrace(); return fileSize; public

17、 static NetworkInfo getNetworkInfo(Context context) ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); return networkInfo; public static boolean isNetConnected(

18、Context context) if (context != null) NetworkInfo ni = getNetworkInfo(context); return ni != null & ni.isAvailable() & ni.isConnected(); return false; /* * get net type name: cmwap/cmnet/wifi/uniwap/uninet/ctnet/ctwap * param context * return */ public static String getNetWorkTypeName(Context contex

19、t) String networkType = null; try NetworkInfo networkInfo = getNetworkInfo(context);/ NULL if (networkInfo != null & networkInfo.isAvailable() String typeName = networkInfo.getTypeName(); / MOBILE/WIFI if (!MOBILE.equalsIgnoreCase(typeName) networkType = typeName; else networkType = networkInfo.getE

20、xtraInfo(); / cmwap/cmnet/wifi/uniwap/uninet if (networkType = null) networkType = typeName + #; catch (Exception e) e.printStackTrace(); return networkType; public static Bitmap getNetBitmap(String url) return downloadNetBitmap(url); public static InputStream downloadNetStream(String url) InputStre

21、am input = null; int retryTimes = 0; do try HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setDoInput(true); con.connect(); input = con.getInputStream(); int maxSize = con.getContentLength(); Log.i(TAG, maxSize= + maxSize); return input; catch (MalformedURLException e

22、) e.printStackTrace(); catch (Exception e) e.printStackTrace(); if (input = null) retryTimes+; if (retryTimes RETRY_TIME) try Thread.sleep(1000); Log.i(TAG, downloadNetStream retryTimes= + retryTimes); catch (InterruptedException e1) continue; while (retryTimes RETRY_TIME); return input; public stat

23、ic Bitmap downloadNetBitmap(String url) Bitmap bitmap = null; InputStream inStream = null; try inStream = downloadNetStream(url); if (inStream != null) bitmap = BitmapFactory.decodeStream(inStream); catch (OutOfMemoryError e3) e3.printStackTrace(); catch (Exception e) e.printStackTrace(); finally if

24、(inStream != null) try inStream.close(); catch (IOException e) e.printStackTrace(); return bitmap; public static void saveStreamToFiles(Context context, InputStream is, String fileName) if (is = null) return; byte buffer = new byte1024; int len = -1; try FileOutputStream bos = context.openFileOutput

25、(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 (FileNotFoundException e) e.printStackTrace(); catch (IOException e) e.printStackTrace(); public static Bitmap getHttpBitmap(String url) HttpC

26、lient httpClient = null; HttpGet httpGet = null; InputStream inStream = null; Bitmap bmp = null; int retryTimes = 0; try do try httpClient = getHttpClient(); httpGet = getHttpGetMethod(url, null, null); HttpResponse res = httpClient.execute(httpGet); int statusCode = res.getStatusLine().getStatusCod

27、e(); if (statusCode != HttpStatus.SC_OK) throw new Exception(error statusCode= + statusCode); inStream = res.getEntity().getContent(); bmp = BitmapFactory.decodeStream(inStream); inStream.close(); break; catch (OutOfMemoryError e3) e3.printStackTrace(); catch (HttpException e) e.printStackTrace(); c

28、atch (IOException e) e.printStackTrace(); catch (Exception e) e.printStackTrace(); if (bmp = null) retryTimes+; if (retryTimes RETRY_TIME) try Thread.sleep(1000); Log.w(TAG, downloadBitmap retryTimes= + retryTimes); catch (InterruptedException e3) continue; while (retryTimes RETRY_TIME); catch (Exception e) e.printStackTrace(); finally httpClient = null;

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1