此篇博客只是下载功能的记录demo,如果你还不太了解okhttp可以参考我的另一篇博客 https://www.cnblogs.com/guanxinjing/p/9708575.html
代码部分package okhttpdemo.com.libs.net.httpBase;import androID.util.Log;import org.Json.JsONObject;import java.io.file;import java.io.fileOutputStream;import java.io.IOException;import java.io.inputStream;import java.io.RandomAccessfile;import java.nio.MappedByteBuffer;import java.nio.channels.fileChannel;import okhttp3.Call;import okhttp3.Callback;import okhttp3.FormBody;import okhttp3.MediaType;import okhttp3.OkhttpClIEnt;import okhttp3.Request;import okhttp3.Requestbody;import okhttp3.Response;import okhttp3.ResponseBody;import okhttpdemo.com.libs.net.httpBase.Listener.httpDownListener;/** *@content: okhttp的下载功能工具类 (分别包含:1.无断点续传的get下载 2.有断点续传的get下载 3.无断点续传的post下载 4.有断点续传的post下载) *@time:2018-12-12 *@build:z */public class OkhttpDownUtil { private static final String TAG = "OkhttpDownUtil"; private Call mCall; private long mAlreadyDownLength = 0;//已经下载长度 private long mTotalLength = 0;//整体文件大小 private int mSign = 0; //标记当前运行的是那个方法 private String mDownUrl;//下载网络地址 private file mPath;//文件保存路径 private JsONObject mJson; private httpDownListener mhttpDownListener;//下载进度接口回调 /** * 没有断点续传功能的get请求下载 * @param downUrl 下载网络地址 * @param savefilePathAndname 保存路径 */ public voID getDownRequest(final String downUrl, final file savefilePathAndname, final httpDownListener Listener) { synchronized (this) { new Thread(new Runnable() { @OverrIDe public voID run() { mSign = 1; mDownUrl = downUrl; mPath = savefilePathAndname; mhttpDownListener = Listener; mAlreadyDownLength = 0; Request request = new Request.Builder() .url(mDownUrl) .get() .build(); mCall = OkhttpClIEntCreate.CreateClIEnt().newCall(request);//构建了一个完整的http请求 mCall.enqueue(new Callback() { @OverrIDe public voID onFailure(Call call, IOException e) { if (mhttpDownListener != null) { mhttpDownListener.onFailure(call, e); } } @OverrIDe public voID onResponse(Call call, Response response) throws IOException { ResponseBody responseBody = response.body(); mTotalLength = responseBody.contentLength();//下载文件的总长度 inputStream inp = responseBody.byteStream(); fileOutputStream fileOutputStream = new fileOutputStream(mPath); try { byte[] bytes = new byte[2048]; int len = 0; while ((len = inp.read(bytes)) != -1) { mAlreadyDownLength = mAlreadyDownLength + len; fileOutputStream.write(bytes, 0, len); if (mhttpDownListener != null) { mhttpDownListener.onResponse(call, response, mTotalLength, mAlreadyDownLength); } } } catch (Exception e) { Log.e(TAG, "Get下载异常"); } finally { fileOutputStream.close(); inp.close(); Log.e(TAG, "流关闭"); } } }); } }).start(); } } /** * 有断点续传功能的get下载 * @param downUrl 下载地址 * @param savefilePathAndname 保存路径 * @param Listener 进度监听 */ public voID get@R_703_5026@DownRequest(final String downUrl, final file savefilePathAndname, final httpDownListener Listener){ synchronized (this) { new Thread(new Runnable() { @OverrIDe public voID run() { mSign = 2; mDownUrl = downUrl; mPath = savefilePathAndname; mhttpDownListener = Listener; Request request = new Request.Builder() .url(mDownUrl) .header("RANGE", "bytes=" + mAlreadyDownLength + "-") .build(); mCall = OkhttpClIEntCreate.CreateClIEnt().newCall(request);//构建了一个完整的http请求 mCall.enqueue(new Callback() { //发送请求 @OverrIDe public voID onFailure(Call call, IOException e) { if (mhttpDownListener != null) { mhttpDownListener.onFailure(call, e); } Log.e(TAG, "onFailure: 异常报错=" + e.toString()); } @OverrIDe public voID onResponse(Call call, Response response) throws IOException { ResponseBody responseBody = response.body(); inputStream inputStream = responseBody.byteStream();//得到输入流 RandomAccessfile randomAccessfile = new RandomAccessfile(mPath, "rw");//得到任意保存文件处理类实例 if (mTotalLength == 0){ mTotalLength = responseBody.contentLength();//得到文件的总字节大小 randomAccessfile.setLength(mTotalLength);//预设创建一个总字节的占位文件 } if (mAlreadyDownLength != 0){ randomAccessfile.seek(mAlreadyDownLength); } byte[] bytes = new byte[2048]; int len = 0; try { while ((len = inputStream.read(bytes)) != -1) { randomAccessfile.write(bytes,0,len); mAlreadyDownLength = mAlreadyDownLength + len; if (mhttpDownListener != null) { mhttpDownListener.onResponse(call, response, mTotalLength, mAlreadyDownLength); } } } catch (Exception e) { Log.e(TAG, "Get下载异常"); } finally { mAlreadyDownLength = randomAccessfile.getfilePointer();//记录当前保存文件的位置 randomAccessfile.close(); inputStream.close(); Log.e(TAG, "流关闭 下载的位置="+mAlreadyDownLength); } } }); } }).start(); } } /** * 没有断点续传的post下载 * @param downUrl * @param savefilePathAndname * @param Json * @param Listener */ public voID postDownRequest(final String downUrl, final file savefilePathAndname, final JsONObject Json,final httpDownListener Listener){ synchronized (this){ new Thread(new Runnable() { @OverrIDe public voID run() { mSign = 3; mDownUrl = downUrl; mPath = savefilePathAndname; mJson = Json; mhttpDownListener = Listener; mAlreadyDownLength = 0; Request request = new Request.Builder() .url(mDownUrl) .post(changeJsON(Json)) .build(); mCall = OkhttpClIEntCreate.CreateClIEnt().newCall(request); mCall.enqueue(new Callback() { @OverrIDe public voID onFailure(Call call, IOException e) { if (mhttpDownListener!=null){ mhttpDownListener.onFailure(call,e); } } @OverrIDe public voID onResponse(Call call, Response response) throws IOException { ResponseBody responseBody = response.body(); mTotalLength = responseBody.contentLength(); inputStream inputStream = responseBody.byteStream(); fileOutputStream fileOutputStream = new fileOutputStream(mPath); byte[] bytes = new byte[2048]; int len = 0; try { while ((len = inputStream.read(bytes)) != -1) { fileOutputStream.write(bytes, 0, len); mAlreadyDownLength = mAlreadyDownLength + len; if (mhttpDownListener != null) { mhttpDownListener.onResponse(call, response, mTotalLength, mAlreadyDownLength); } } }catch (Exception e){ Log.e(TAG, "Post下载异常"); }finally { fileOutputStream.close(); inputStream.close(); Log.e(TAG, "流关闭"); } } }); } }).start(); } } /** * 支持断点续传的post下载 * @param downUrl 下载网址 * @param savefilePathAndname 文件保存路径 * @param Json 参数 * @param Listener 接口回调 */ public voID post@R_703_5026@DownRequest(final String downUrl, final file savefilePathAndname, final JsONObject Json, final httpDownListener Listener){ synchronized (this){ new Thread(new Runnable() { @OverrIDe public voID run() { mSign = 4; mDownUrl = downUrl; mPath = savefilePathAndname; mJson = Json; mhttpDownListener = Listener; Request request = new Request.Builder() .url(mDownUrl) .header("RANGE","bytes="+mAlreadyDownLength+"-") .post(changeJsON(Json)) .build(); mCall = OkhttpClIEntCreate.CreateClIEnt().newCall(request); mCall.enqueue(new Callback() { @OverrIDe public voID onFailure(Call call, IOException e) { if (mhttpDownListener != null){ mhttpDownListener.onFailure(call,e); } } @OverrIDe public voID onResponse(Call call, Response response) throws IOException { ResponseBody responseBody = response.body(); inputStream inputStream = responseBody.byteStream(); RandomAccessfile randomAccessfile = new RandomAccessfile(mPath,"rw"); if (mTotalLength == 0){ mTotalLength = responseBody.contentLength(); randomAccessfile.setLength(mTotalLength); } if (mAlreadyDownLength!=0){ randomAccessfile.seek(mAlreadyDownLength); } byte[] bytes = new byte[2048]; int len = 0; try { while ((len = inputStream.read(bytes)) != -1) { randomAccessfile.write(bytes, 0, len); mAlreadyDownLength = mAlreadyDownLength + len; if (mhttpDownListener != null) { mhttpDownListener.onResponse(call, response, mTotalLength, mAlreadyDownLength); } } }catch (Exception e){ Log.e(TAG, "Post下载异常"); }finally { mAlreadyDownLength = randomAccessfile.getfilePointer(); randomAccessfile.close(); inputStream.close(); Log.e(TAG, "流关闭 下载的位置="+mAlreadyDownLength); } } }); } }).start(); } } /** * 恢复下载 */ public voID resume(){ if (mSign==0){ return; } switch (mSign){ case 1: getDownRequest(mDownUrl,mPath,mhttpDownListener); break; case 2: get@R_703_5026@DownRequest(mDownUrl,mPath,mhttpDownListener); break; case 3: postDownRequest(mDownUrl,mPath,mJson,mhttpDownListener); break; case 4: post@R_703_5026@DownRequest(mDownUrl,mPath,mJson,mhttpDownListener); break; default: break; } } /** * 暂停下载 */ public voID stop(){ if (mCall!=null){ mCall.cancel(); } } /** * 删除下载文件 */ public voID deleteCurrentfile(){ if (mPath == null){ Log.e(TAG, "deleteCurrentfile error : 没有路径"); return; } if (!mPath.exists()){ Log.e(TAG, "deleteCurrentfile error: 文件不存在"); return; } mPath.delete(); mAlreadyDownLength = 0; mTotalLength = 0; mSign = 0; } /** * 销毁 */ public voID destroy(){ if (mCall!=null){ mCall.cancel(); mCall = null; } mSign = 0; mDownUrl = null; mPath = null; mhttpDownListener = null; mAlreadyDownLength = 0; mTotalLength = 0; } /** * 转换Json参数为Requestbody * @param JsonParam Json对象 * @return Requestbody */ private Requestbody changeJsON(JsONObject JsonParam){ Requestbody requestbody = FormBody.create(MediaType.parse("application/Json; charset=utf-8") , String.valueOf(JsonParam)); return requestbody; }}
总结
以上是内存溢出为你收集整理的Android 开发 框架系列 OkHttp文件下载功能实现(含断点续传)全部内容,希望文章能够帮你解决Android 开发 框架系列 OkHttp文件下载功能实现(含断点续传)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)