前言

  此篇博客只是下载功能的记录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) {
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, "流关闭");
}
}
});
} /**
* 有断点续传功能的get下载
* @param downUrl 下载地址
* @param saveFilePathAndName 保存路径
* @param listener 进度监听
*/
public void getRenewalDownRequest(final String downUrl, final File saveFilePathAndName, final HttpDownListener listener){
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);
} }
});
} /**
* 没有断点续传的post下载
* @param downUrl
* @param saveFilePathAndName
* @param json
* @param listener
*/
public void postDownRequest(final String downUrl, final File saveFilePathAndName, final JSONObject json,final HttpDownListener listener){
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, "流关闭"); } } }); } /**
* 支持断点续传的post下载
* @param downUrl 下载网址
* @param saveFilePathAndName 文件保存路径
* @param json 参数
* @param listener 接口回调
*/
public void postRenewalDownRequest(final String downUrl, final File saveFilePathAndName, final JSONObject json, final HttpDownListener listener){
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);
} }
});
} /**
* 恢复下载
*/
public void resume(){
if (mSign==0){
return;
}
switch (mSign){
case 1:
getDownRequest(mDownUrl,mPath,mHttpDownListener);
break;
case 2:
getRenewalDownRequest(mDownUrl,mPath,mHttpDownListener);
break;
case 3:
postDownRequest(mDownUrl,mPath,mJson,mHttpDownListener);
break;
case 4:
postRenewalDownRequest(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文件下载功能实现(含断点续传)的更多相关文章

  1. Android 开发 框架系列 OkHttp拦截器

    前言 此篇博客只讲解okhttp的拦截器功能的详细使用,如果你还不太了解okhttp可以参考我另外一篇博客 Android 开发 框架系列 OkHttp使用详解 添加Interceptor的简单例子 ...

  2. Android 开发 框架系列 OkHttp使用详解

    简介 okhttp是一个第三方类库,用于android中请求网络.这是一个开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso和LeakCanary) . ...

  3. Android 开发 框架系列 OkHttp文件上传功能实现(含断点续传)

    前言 此篇博客只是上传功能的记录demo,如果你还不太了解okhttp可以参考我的另一篇博客https://www.cnblogs.com/guanxinjing/p/9708575.html 代码部 ...

  4. Android 开发 框架系列 Google的ORM框架 Room

    目录 简介 导入工程 使用流程概况 一个简单的小Demo 深入学习 @Entity使用 自定义表名 tableName  自定义字段名@ColumnInfo 主键 @PrimaryKey 索引 @In ...

  5. android 开发 框架系列 使用 FileDownloader 实现检查更新的功能class

    首先介绍一下FileDownloader GH :https://github.com/lingochamp/FileDownloader/blob/master/README-zh.md FileD ...

  6. Android 开发 框架系列 百度语音合成

    官方文档:http://ai.baidu.com/docs#/TTS-Android-SDK/6d5d6899 官方百度语音合成控制台:https://cloud.baidu.com/product/ ...

  7. Android 开发 框架系列 EventBus 事件总线

    介绍 GitHub:https://github.com/greenrobot/EventBus 先聊聊EventBus 线程总线是干什么的,使用环境,优点.缺点. 干什么的? 一句话,简单统一数据传 ...

  8. Android 开发 框架系列 glide-transformations 图片处理基本使用

    首先简单的介绍一下Gilde作用范围.Gilde功能十分强大,它可以实现图片处理.图片本地加载.图片网络加载.位图加载.图片内存缓存.图片磁盘缓存.Gif图片加载.使用简单轻松,轻松的后是它强大的心, ...

  9. Android 开发 框架系列 Android-Universal-Image-Loader 图片加载使用demo

    Android-Universal-Image-Loader github地址:https://github.com/nostra13/Android-Universal-Image-Loader 加 ...

随机推荐

  1. No parameter name specified for argument of type

    在使用SpringMVC绑定基本类型(如String,Integer等)参数时,应通过@RequestParam注解指定具体的参数名称,否则,当源代码在非debug模式下编译后,运行时会引发Handl ...

  2. what have we learnt in day five

    what is file? virtual unit offered by operation system steps to open file 1.find the file_path(file_ ...

  3. 精选 Dubbo RPC 面试题,比较全面,含答案

    精选 Dubbo RPC 面试题,比较全面,含答案 hu1991die 搜云库技术团队 搜云库技术团队 微信号 souyunku 功能介绍 专注于分享最有价值的互联网技术干货文章,内容覆盖,Java后 ...

  4. html-基础知识二

    form 功能:向服务器传输数据,实现用户和web 服务器的交互 一.表单属性 accept-charset: 规定在提交表单中使用的字符集 action:规定向何处提交表单地址(url) autoc ...

  5. Linux grep return code

    The exit code is 1 because nothing was matched by grep. EXIT STATUS The exit status is 0 if selected ...

  6. 机器学习改善Interpretability的几个技术

    改善机器学习可解释性的技术和方法 尽管透明性和道德问题对于现场的数据科学家来说可能是抽象的,但实际上,可以做一些实际的事情来提高算法的可解释性 算法概括 首先是提高概括性.这听起来很简单,但并非那么简 ...

  7. PHP算法之电话号码的字母组合

    给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合. 给出数字到字母的映射如下(与电话按键相同).注意 1 不对应任何字母. 示例: 输入:"23"输出:[" ...

  8. systemctl命令的使用及服务状态的查看

    二.systemctl命令 systemctl list-units            ##列出当前系统服务的状态 systemctl list-unit-files       ##列出服务的开 ...

  9. Linux CentOS-7.0上安装Tomcat7

    Linux CentOS-7.0上安装Tomcat7   安装说明 安装环境:CentOS-7.0.1406安装方式:源码安装 软件:apache-tomcat-7.0.29.tar.gz 下载地址: ...

  10. CSP-S2019旅游记

    CSP-S2019 你问我为什么写旅游记? 因为好像除了旅游我今年啥都没干 Day0 校内模拟一直被吊锤,考前几场几乎要爆零 这提莫就不是什么好兆头 在家二刷水淹东京完回学校,带了一大堆家当上车 去广 ...