OkHttp学习(2)--异步下载图片、文件(拦截器重写Response方法实现下载进度获取)

本文主要是介绍OkHttp学习(2)--异步下载图片、文件(拦截器重写Response方法实现下载进度获取),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

OkHttp学习(1)–>>同步和异步(get、post键值对、post带map、请求头体封装json)

Volley学习链接—想了解Volley的可以看我这5篇

今天来了解下okHttp如何进行图片、文件下载的
首先在OkHttpManger弄一个单利模式,初始化一个OkHttpClient,然后放进去一个handler,线程更新ui使用

private Handler okHttpHandler;private OkHttpClient mOkHttpClient;private OkHttpManger(){this.mOkHttpClient = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS)//连接超时限制.writeTimeout(30, TimeUnit.SECONDS)//写入超时.readTimeout(30, TimeUnit.SECONDS)//读取超时.build();this.okHttpHandler = new Handler(Looper.getMainLooper());}public static final OkHttpManger getInstance(){return SingleFactory.manger;}private static final class SingleFactory{private static final OkHttpManger manger = new OkHttpManger();}

然后直接执行下载方法

 public void downloadAsync(final String url, final String destFileDir,final OKHttpUICallback.ProgressCallback downListener) throws IOException {File file = new File(destFileDir,getFileName(url));if(!file.exists()){file.createNewFile();}downloadAsync(url, file, downListener);}

参数1为图片的url,我们这里用了http://img.mukewang.com/55249cf30001ae8a06000338.jpg来测试,
参数2destFileDir这个是下载完毕保存到手机的目录地址,我们传入的参数如下:

Config.getDirFile("download").getAbsolutePath()

这里做了一些目录的设置

public static File getDirFile(String subFileName){if(isSDMounted()){return mkdirsFolder(getSDirAbsolutePath() + "/Seeker/" + subFileName);}return null;}public static boolean isSDMounted(){return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);}public static File mkdirsFolder(String path){File file = new File(path);if(!file.exists()){return file.mkdirs()?file:null;}return file;}public static String getSDirAbsolutePath(){return Environment.getExternalStorageDirectory().getAbsolutePath();}

就是在sd卡根目录下创建Seeker/download文件夹,下载的图片就存在download文件夹下
目录有了,下载完毕图片,我们需要起一个名字把:

 File file = new File(destFileDir,getFileName(url));if(!file.exists()){file.createNewFile();}
 private String getFileName(String url){int lastSeparaorIndex = url.lastIndexOf("/");return (lastSeparaorIndex < 0) ? url : url.substring(lastSeparaorIndex + 1, url.length());}

然后正式进入下载的代码

public void downloadAsync(final String url, final File downFile,final OKHttpUICallback.ProgressCallback downListener) throws IOException {OkHttpClient downLoadClient = mOkHttpClient.newBuilder().addInterceptor(new Interceptor() {@Overridepublic Response intercept(Chain chain) throws IOException {//拦截Response origin = chain.proceed(chain.request());//包装响应体return origin.newBuilder().body(new ProgressBody.ProgressResponseBody(origin.body(), downListener, okHttpHandler)).build();}}).build();final Request request = new Request.Builder().url(url).build();downLoadClient.newCall(request).enqueue(new OKHttpThreadCallback(okHttpHandler,downListener,true).setFile(downFile));}

我们来看下代码里面做了什么操作?我们首先想到的是弄一个接口把
OKHttpUICallback.ProgressCallback downListener接口有3个接口方法,意思很明显。

 public interface ProgressCallback{void onSuccess(Call call, Response response, String path);void onProgress(long byteReadOrWrite, long contentLength, boolean done);void onError(Call call, IOException e);}

okhttp实现了拦截器Interceptor,这个是什么意思呢?

Interceptors area powerful mechanism that can monitor, rewrite, and retry calls.
拦截器可以用来转换,重试,重写请求的机制。这是官方的定义。
一句话就是对请求、相应加上自己的代码,重写方法

OkHttpClient downLoadClient = mOkHttpClient.newBuilder().addInterceptor(new Interceptor() {@Overridepublic Response intercept(Chain chain) throws IOException {//拦截Response origin = chain.proceed(chain.request());//包装响应体return origin.newBuilder().body(new ProgressBody.ProgressResponseBody(origin.body(), downListener, okHttpHandler)).build();}}).build();

这里就是用到了拦截器,大概意思就是,对请求响应体,进行二次包装,比如请求图片、文件的进度问题
我们看下我们做了什么操作呢?

new ProgressBody.ProgressResponseBody(origin.body(), downListener, okHttpHandler)
  @Overridepublic BufferedSource source() {if(bufferedSource == null){bufferedSource = Okio.buffer(source(responseBody.source()));}return bufferedSource;}/*** 读取,回调进度接口* @return*/private Source source(Source source){return new ForwardingSource(source) {//读取当前获取的字节数long totalBytesRead = 0L;@Overridepublic long read(Buffer sink, long byteCount) throws IOException {final long byteRead =  super.read(sink, byteCount);if(mHandler != null && mListener != null){//增加当前读取的字节数,如果读取完成则返回-1totalBytesRead += byteRead != -1?byteRead:0;//回调,若是contentLength()不知道长度,则返回-1mHandler.post(new Runnable() {@Overridepublic void run() {mListener.onProgress(totalBytesRead, contentLength(), byteRead == -1);}});}return byteRead;}};}

mListener.onProgress(totalBytesRead, contentLength(), byteRead == -1);就是对请求进度的一个对外通讯,告诉ui界面可以做一些操作,比如进度条之类的

然后继续看那个下载的入口方法里面的

downLoadClient.newCall(request).enqueue(new OKHttpThreadCallback(okHttpHandler,downListener,true).setFile(downFile));

这里面做了什么操作呢?

 @Overridepublic void onFailure(final Call call, final IOException e) {if(UICallback != null && UIHandler != null){UIHandler.post(new Runnable() {@Overridepublic void run() {UICallback.onError(call,e);}});}}@Overridepublic void onResponse(Call call, Response response) throws IOException {if(isDownload){download(call,response);}else{postSuccess(call,response);}}

就是在请求相应里面,进行sd写入

private void download(Call call, Response response) throws IOException {if(downFile == null){throw new NullPointerException("downFile == null");}byte[] buffer = new byte[2048];InputStream is = response.body().byteStream();int len;FileOutputStream fos = new FileOutputStream(downFile);while ((len = is.read(buffer)) != -1){fos.write(buffer,0,len);}fos.flush();if(is != null){is.close();}if (fos != null){fos.close();}postSuccess(call,null);}

然后在主界面进行接口方法实现,去实现其他需要处理的

 UICallback.onSuccess(call, response,downFile == null?null:downFile.getAbsolutePath());

如下是下载过程的log

09-01 18:05:55.398 22636-22636/com.example.administrator.myapplication I/MainActivity: downloadAsync
09-01 18:05:55.826 22636-22636/com.example.administrator.myapplication I/MainActivity: byteReadOrWrite:798,contentLength:471776,done:false
................
...............
09-01 18:06:04.795 22636-22636/com.example.administrator.myapplication I/MainActivity: byteReadOrWrite:471776,contentLength:471776,done:true
09-01 18:06:04.797 22636-22636/com.example.administrator.myapplication I/MainActivity: path:/storage/emulated/0/Seeker/download/55249cf30001ae8a06000338.jpg

另外附下载截图一张:
这里写图片描述

//以下是代码堆积区//

MainActivity

package com.example.administrator.myapplication;import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;import java.io.IOException;import okhttp3.Call;
import okhttp3.Response;public class MainActivity extends AppCompatActivity implements View.OnClickListener {Button downloadAsync;ImageView imageView;String url = "http://img.mukewang.com/55249cf30001ae8a06000338.jpg";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);imageView = (ImageView) findViewById(R.id.imageView);downloadAsync = (Button) findViewById(R.id.downloadAsync);downloadAsync.setOnClickListener(this);}@Overridepublic void onClick(View v) {switch (v.getId()){case R.id.downloadAsync:Log.i("MainActivity","downloadAsync");//下载图片try {OkHttpManger.getInstance().downloadAsync(url, Config.getDirFile("download").getAbsolutePath(), new OKHttpUICallback.ProgressCallback() {@Overridepublic void onSuccess(Call call, Response response, String path) {Log.i("MainActivity","path:"+path);}@Overridepublic void onProgress(long byteReadOrWrite, long contentLength, boolean done) {Log.i("MainActivity","byteReadOrWrite:"+byteReadOrWrite+",contentLength:"+contentLength+",done:"+done);}@Overridepublic void onError(Call call, IOException e) {Log.i("MainActivity","onError");}});} catch (IOException e) {e.printStackTrace();}break;}}
}

OkHttpManger

package com.example.administrator.myapplication;import android.os.Handler;
import android.os.Looper;
import android.util.Log;import com.alibaba.fastjson.JSON;import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;/*** OkHttp 工具类,* get的同步异步请求* post的json字符串同步异步上传* post的键值对同步异步上传* post文件异步上传,回调结果以及进度* 异步下载文件,回调结果以及进度** Created by Seeker on 2016/6/24.*/
public final class OkHttpManger {private static final String TAG = "OkHttpManger";private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");private Handler okHttpHandler;private OkHttpClient mOkHttpClient;private OkHttpManger(){this.mOkHttpClient = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS)//连接超时限制.writeTimeout(30, TimeUnit.SECONDS)//写入超时.readTimeout(30, TimeUnit.SECONDS)//读取超时.build();this.okHttpHandler = new Handler(Looper.getMainLooper());}public static final OkHttpManger getInstance(){return SingleFactory.manger;}private static final class SingleFactory{private static final OkHttpManger manger = new OkHttpManger();}/*** 异步下载文件,实现了下载进度的提示** @param url* @param destFileDir 文件存储根路径* @param downListener*/public void downloadAsync(final String url, final String destFileDir,final OKHttpUICallback.ProgressCallback downListener) throws IOException {File file = new File(destFileDir,getFileName(url));if(!file.exists()){file.createNewFile();}downloadAsync(url, file, downListener);}/*** 获取文件名** @param path*/private String getFileName(String url){int lastSeparaorIndex = url.lastIndexOf("/");return (lastSeparaorIndex < 0) ? url : url.substring(lastSeparaorIndex + 1, url.length());}/*** 异步下载文件,实现了下载进度的提示* @param url* @param downFile:存储文件(文件存储绝对路径文件)* @param downListener* @throws IOException*/public void downloadAsync(final String url, final File downFile,final OKHttpUICallback.ProgressCallback downListener) throws IOException {OkHttpClient downLoadClient = mOkHttpClient.newBuilder().addInterceptor(new Interceptor() {@Overridepublic Response intercept(Chain chain) throws IOException {//拦截Response origin = chain.proceed(chain.request());//包装响应体return origin.newBuilder().body(new ProgressBody.ProgressResponseBody(origin.body(), downListener, okHttpHandler)).build();}}).build();final Request request = new Request.Builder().url(url).build();downLoadClient.newCall(request).enqueue(new OKHttpThreadCallback(okHttpHandler,downListener,true).setFile(downFile));}}

ProgressBody

package com.example.administrator.myapplication;import android.os.Handler;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.ForwardingSink;
import okio.ForwardingSource;
import okio.Okio;
import okio.Sink;
import okio.Source;/*** Created by Safly on 2016/9/1.*/
public final class ProgressBody {/*** 包装响应体,用于处理提示下载进度** Created by Seeker on 2016/6/29.*/public static final class ProgressResponseBody extends ResponseBody {//实际待包装的响应体private final ResponseBody responseBody;//进度回调接口private OKHttpUICallback.ProgressCallback mListener;//包装完成的BufferedSourceprivate BufferedSource bufferedSource;//传递下载进度到主线程private Handler mHandler;public ProgressResponseBody(ResponseBody responseBody, OKHttpUICallback.ProgressCallback listener, Handler handler){this.responseBody = responseBody;this.mListener = listener;this.mHandler = handler;}@Overridepublic MediaType contentType() {return responseBody.contentType();}@Overridepublic long contentLength() {return responseBody.contentLength();}@Overridepublic BufferedSource source() {if(bufferedSource == null){bufferedSource = Okio.buffer(source(responseBody.source()));}return bufferedSource;}/*** 读取,回调进度接口* @return*/private Source source(Source source){return new ForwardingSource(source) {//读取当前获取的字节数long totalBytesRead = 0L;@Overridepublic long read(Buffer sink, long byteCount) throws IOException {final long byteRead =  super.read(sink, byteCount);if(mHandler != null && mListener != null){//增加当前读取的字节数,如果读取完成则返回-1totalBytesRead += byteRead != -1?byteRead:0;//回调,若是contentLength()不知道长度,则返回-1mHandler.post(new Runnable() {@Overridepublic void run() {mListener.onProgress(totalBytesRead, contentLength(), byteRead == -1);}});}return byteRead;}};}}}

OKHttpThreadCallback

package com.example.administrator.myapplication;import android.os.Handler;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;public final class OKHttpThreadCallback implements Callback {private Handler UIHandler;private OKHttpUICallback.ProgressCallback UICallback;private boolean isDownload;private File downFile;public OKHttpThreadCallback(Handler handler, OKHttpUICallback.ProgressCallback callback, boolean isDownload){this.UIHandler = handler;this.UICallback = callback;this.isDownload = isDownload;}@Overridepublic void onFailure(final Call call, final IOException e) {if(UICallback != null && UIHandler != null){UIHandler.post(new Runnable() {@Overridepublic void run() {UICallback.onError(call,e);}});}}@Overridepublic void onResponse(Call call, Response response) throws IOException {if(isDownload){download(call,response);}else{postSuccess(call,response);}}/*** 设置保存file* @param file*/public OKHttpThreadCallback setFile(File file){this.downFile = file;return this;}/*** 获取下载数据并写入文件* @param response*/private void download(Call call, Response response) throws IOException {if(downFile == null){throw new NullPointerException("downFile == null");}byte[] buffer = new byte[2048];InputStream is = response.body().byteStream();int len;FileOutputStream fos = new FileOutputStream(downFile);while ((len = is.read(buffer)) != -1){fos.write(buffer,0,len);}fos.flush();if(is != null){is.close();}if (fos != null){fos.close();}postSuccess(call,null);}/*** 回调成功信息* @param call* @param response*/private void postSuccess(final Call call, final Response response){if(UICallback != null && UIHandler != null){UIHandler.post(new Runnable() {@Overridepublic void run() {UICallback.onSuccess(call, response,downFile == null?null:downFile.getAbsolutePath());}});}}
}

Config

package com.example.administrator.myapplication;import android.os.Environment;import java.io.File;public class Config {public static File getDirFile(String subFileName){if(isSDMounted()){return mkdirsFolder(getSDirAbsolutePath() + "/Seeker/" + subFileName);}return null;}public static boolean isSDMounted(){return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);}public static File mkdirsFolder(String path){File file = new File(path);if(!file.exists()){return file.mkdirs()?file:null;}return file;}public static String getSDirAbsolutePath(){return Environment.getExternalStorageDirectory().getAbsolutePath();}}

最后看一个接口

package com.example.administrator.myapplication;import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;import okhttp3.Call;
import okhttp3.Response;/*** Created by safly on 2016/9/1.* 回调主线程的接口*/
public class OKHttpUICallback {/*** 带有进度的上传、下载回调接口*/public interface ProgressCallback{void onSuccess(Call call, Response response, String path);void onProgress(long byteReadOrWrite, long contentLength, boolean done);void onError(Call call, IOException e);}
}

这篇关于OkHttp学习(2)--异步下载图片、文件(拦截器重写Response方法实现下载进度获取)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1125252

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

常用的jdk下载地址

jdk下载地址 安装方式可以看之前的博客: mac安装jdk oracle 版本:https://www.oracle.com/java/technologies/downloads/ Eclipse Temurin版本:https://adoptium.net/zh-CN/temurin/releases/ 阿里版本: github:https://github.com/

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time