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