android中实现OkHttp下载文件并带进度条
作者:Gary__123456 时间:2022-04-11 17:20:20
OkHttp是比较火的网络框架,它支持同步与异步请求,支持缓存,可以拦截,更方便下载大文件与上传文件的操作。下面我们用OkHttp来下载文件并带进度条!
相关资料:
官网地址:http://square.github.io/okhttp/
github源码地址:https://github.com/square/okhttp
一、服务器端简单搭建
可以参考搭建本地Tomcat服务器及相关配置 这篇文章。
新建项目OkHttpServer,在WebContent目录下新建downloadfile目录,将要下载的jpg文件放在项目下。如下图:
启动服务器,文件下载地址为http://localhost:8080/OkHttpServer/download/2.jpg 。这样我们服务器就搭好了。
二、Android端
下面我们进入正题。
1.build.gradle的dependencies配置如下
compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okio:okio:1.7.0'
2.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.huang.myokhttp.MainActivity">
<Button
android:id="@+id/ok_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="下载文件" />
<TextView
android:id="@+id/download_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="0" />
<ProgressBar
android:id="@+id/download_progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100" />
</RelativeLayout>
3.编写OkHttpUtil如下:
private static OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10000, TimeUnit.MILLISECONDS)
.readTimeout(10000,TimeUnit.MILLISECONDS)
.writeTimeout(10000,TimeUnit.MILLISECONDS).build();
//下载文件方法
public static void downloadFile(String url, final ProgressListener listener, Callback callback){
//增加 *
OkHttpClient client = okHttpClient.newBuilder().addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
return response.newBuilder().body(new ProgressResponseBody(response.body(),listener)).build();
}
}).build();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(callback);
}
4.上面代码中的ProgressResponseBody是自己编写的类,ProgressListener 是监听的接口:
ProgressListener 接口
public interface ProgressListener {
//已完成的 总的文件长度 是否完成
void onProgress(long currentBytes, long contentLength, boolean done);
}
ProgressResponseBody继承ResponseBody ,返回监听进度
public class ProgressResponseBody extends ResponseBody {
public static final int UPDATE = 0x01;
public static final String TAG = ProgressResponseBody.class.getName();
private ResponseBody responseBody;
private ProgressListener mListener;
private BufferedSource bufferedSource;
private Handler myHandler;
public ProgressResponseBody(ResponseBody body, ProgressListener listener) {
responseBody = body;
mListener = listener;
if (myHandler==null){
myHandler = new MyHandler();
}
}
/**
* 将进度放到主线程中显示
*/
class MyHandler extends Handler {
public MyHandler() {
super(Looper.getMainLooper());
}
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case UPDATE:
ProgressModel progressModel = (ProgressModel) msg.obj;
//接口返回
if (mListener!=null)mListener.onProgress(progressModel.getCurrentBytes(),progressModel.getContentLength(),progressModel.isDone());
break;
}
}
}
@Override
public MediaType contentType() {
return responseBody.contentType();
}
@Override
public long contentLength() {
return responseBody.contentLength();
}
@Override
public BufferedSource source() {
if (bufferedSource==null){
bufferedSource = Okio.buffer(mySource(responseBody.source()));
}
return bufferedSource;
}
private Source mySource(Source source) {
return new ForwardingSource(source) {
long totalBytesRead = 0L;
@Override
public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead = super.read(sink, byteCount);
totalBytesRead +=bytesRead!=-1?bytesRead:0;
//发送消息到主线程,ProgressModel为自定义实体类
Message msg = Message.obtain();
msg.what = UPDATE;
msg.obj = new ProgressModel(totalBytesRead,contentLength(),totalBytesRead==contentLength());
myHandler.sendMessage(msg);
return bytesRead;
}
};
}
}
5.MainActivity的代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
public static final String TAG = MainActivity.class.getName();
private ProgressBar download_progress;
private TextView download_text;
public static String basePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/okhttp";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
download_progress = (ProgressBar) findViewById(R.id.download_progress);
download_text = (TextView) findViewById(R.id.download_text);
findViewById(R.id.ok_download).setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.ok_download:
String url = "http://192.168.0.104:8080/OkHttpServer/download/2.jpg";
final String fileName = url.split("/")[url.split("/").length - 1];
Log.i(TAG, "fileName==" + fileName);
OkHttpUtil.downloadFile(url, new ProgressListener() {
@Override
public void onProgress(long currentBytes, long contentLength, boolean done) {
Log.i(TAG, "currentBytes==" + currentBytes + "==contentLength==" + contentLength + "==done==" + done);
int progress = (int) (currentBytes * 100 / contentLength);
download_progress.setProgress(progress);
download_text.setText(progress + "%");
}
}, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null) {
InputStream is = response.body().byteStream();
FileOutputStream fos = new FileOutputStream(new File(basePath + "/" + fileName));
int len = 0;
byte[] buffer = new byte[2048];
while (-1 != (len = is.read(buffer))) {
fos.write(buffer, 0, len);
}
fos.flush();
fos.close();
is.close();
}
}
});
break;
}
}
}
6.最后不要忘了添加权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
源码下载
来源:http://blog.csdn.net/Gary__123456/article/details/74157403
标签:OkHttp,下载,文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
springboot2.5.6集成RabbitMq实现Topic主题模式(推荐)
2021-10-03 22:01:22
![](https://img.aspxhome.com/file/2023/4/83494_0s.png)
Android四种常见布局方式示例教程
2022-05-25 09:35:03
![](https://img.aspxhome.com/file/2023/7/108287_0s.png)
用java在web环境下上传和下载文件的技巧
2021-06-09 18:17:17
C#使用oledb操作excel文件的方法
2023-06-13 19:19:42
基于Avalonia实现自定义弹窗的示例详解
2022-02-27 16:30:45
![](https://img.aspxhome.com/file/2023/0/98290_0s.png)
Android自定义控件实现底部菜单(下)
2023-03-28 15:35:38
![](https://img.aspxhome.com/file/2023/8/137478_0s.jpg)
简单记事本java源码实例
2023-11-26 02:03:17
![](https://img.aspxhome.com/file/2023/4/59744_0s.jpg)
MyBatis-Plus 集成动态多数据源的实现示例
2023-06-26 17:56:35
Android中Gallery和ImageSwitcher的使用实例
2021-05-28 15:52:12
![](https://img.aspxhome.com/file/2023/7/137537_0s.png)
在WCF数据访问中使用缓存提高Winform字段中文显示速度的方法
2022-11-08 10:05:09
![](https://img.aspxhome.com/file/2023/5/125975_0s.png)
monkeyrunner之安卓开发环境搭建教程(1)
2023-02-24 06:24:22
![](https://img.aspxhome.com/file/2023/9/137999_0s.png)
Java进阶必备之多线程编程
2023-12-17 04:24:51
![](https://img.aspxhome.com/file/2023/3/79323_0s.png)
Java包装类原理与用法实例分析
2022-08-15 19:51:44
![](https://img.aspxhome.com/file/2023/9/83429_0s.png)
在Flutter中制作翻转卡片动画的完整实例代码
2023-06-23 23:31:21
浅析Java类和数据结构中常用的方法
2022-03-03 19:39:53
Android编程之交互对话框实例浅析
2021-09-09 04:47:08
Java中ArrayList在foreach里remove的问题详析
2022-08-04 02:30:40
Android实现的仿淘宝购物车demo示例
2023-09-04 08:59:19
![](https://img.aspxhome.com/file/2023/9/110689_0s.png)
java基于UDP实现在线聊天功能
2021-06-08 00:01:44
![](https://img.aspxhome.com/file/2023/3/89603_0s.jpg)
Android Flutter中Offstage组件的使用教程详解
2023-08-20 01:01:44