查看: 450|回复: 0

[Android教程] android中实现OkHttp下载文件并带进度条

发表于 2017-11-28 08:00:01

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配置如下

  1. compile 'com.android.support:appcompat-v7:24.1.1'
  2. compile 'com.squareup.okhttp3:okhttp:3.2.0'
  3. compile 'com.squareup.okio:okio:1.7.0'
复制代码

2.activity_main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:paddingBottom="@dimen/activity_vertical_margin"
  7. android:paddingLeft="@dimen/activity_horizontal_margin"
  8. android:paddingRight="@dimen/activity_horizontal_margin"
  9. android:paddingTop="@dimen/activity_vertical_margin"
  10. tools:context="com.huang.myokhttp.MainActivity">
  11. <Button
  12. android:id="@+id/ok_download"
  13. android:layout_width="match_parent"
  14. android:layout_height="wrap_content"
  15. android:text="下载文件" />
  16. <TextView
  17. android:id="@+id/download_text"
  18. android:layout_width="match_parent"
  19. android:layout_height="wrap_content"
  20. android:gravity="center"
  21. android:text="0" />
  22. <ProgressBar
  23. android:id="@+id/download_progress"
  24. style="?android:attr/progressBarStyleHorizontal"
  25. android:layout_width="match_parent"
  26. android:layout_height="wrap_content"
  27. android:max="100" />
  28. </RelativeLayout>
复制代码

3.编写OkHttpUtil如下:

  1. private static OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10000, TimeUnit.MILLISECONDS)
  2. .readTimeout(10000,TimeUnit.MILLISECONDS)
  3. .writeTimeout(10000,TimeUnit.MILLISECONDS).build();
  4. //下载文件方法
  5. public static void downloadFile(String url, final ProgressListener listener, Callback callback){
  6. //增加拦截器
  7. OkHttpClient client = okHttpClient.newBuilder().addNetworkInterceptor(new Interceptor() {
  8. @Override
  9. public Response intercept(Chain chain) throws IOException {
  10. Response response = chain.proceed(chain.request());
  11. return response.newBuilder().body(new ProgressResponseBody(response.body(),listener)).build();
  12. }
  13. }).build();
  14. Request request = new Request.Builder().url(url).build();
  15. client.newCall(request).enqueue(callback);
  16. }
复制代码

4.上面代码中的ProgressResponseBody是自己编写的类,ProgressListener 是监听的接口:

ProgressListener 接口

  1. public interface ProgressListener {
  2. //已完成的 总的文件长度 是否完成
  3. void onProgress(long currentBytes, long contentLength, boolean done);
  4. }
复制代码

ProgressResponseBody继承ResponseBody ,返回监听进度

  1. public class ProgressResponseBody extends ResponseBody {
  2. public static final int UPDATE = 0x01;
  3. public static final String TAG = ProgressResponseBody.class.getName();
  4. private ResponseBody responseBody;
  5. private ProgressListener mListener;
  6. private BufferedSource bufferedSource;
  7. private Handler myHandler;
  8. public ProgressResponseBody(ResponseBody body, ProgressListener listener) {
  9. responseBody = body;
  10. mListener = listener;
  11. if (myHandler==null){
  12. myHandler = new MyHandler();
  13. }
  14. }
  15. /**
  16. * 将进度放到主线程中显示
  17. */
  18. class MyHandler extends Handler {
  19. public MyHandler() {
  20. super(Looper.getMainLooper());
  21. }
  22. @Override
  23. public void handleMessage(Message msg) {
  24. switch (msg.what){
  25. case UPDATE:
  26. ProgressModel progressModel = (ProgressModel) msg.obj;
  27. //接口返回
  28. if (mListener!=null)mListener.onProgress(progressModel.getCurrentBytes(),progressModel.getContentLength(),progressModel.isDone());
  29. break;
  30. }
  31. }
  32. }
  33. @Override
  34. public MediaType contentType() {
  35. return responseBody.contentType();
  36. }
  37. @Override
  38. public long contentLength() {
  39. return responseBody.contentLength();
  40. }
  41. @Override
  42. public BufferedSource source() {
  43. if (bufferedSource==null){
  44. bufferedSource = Okio.buffer(mySource(responseBody.source()));
  45. }
  46. return bufferedSource;
  47. }
  48. private Source mySource(Source source) {
  49. return new ForwardingSource(source) {
  50. long totalBytesRead = 0L;
  51. @Override
  52. public long read(Buffer sink, long byteCount) throws IOException {
  53. long bytesRead = super.read(sink, byteCount);
  54. totalBytesRead +=bytesRead!=-1?bytesRead:0;
  55. //发送消息到主线程,ProgressModel为自定义实体类
  56. Message msg = Message.obtain();
  57. msg.what = UPDATE;
  58. msg.obj = new ProgressModel(totalBytesRead,contentLength(),totalBytesRead==contentLength());
  59. myHandler.sendMessage(msg);
  60. return bytesRead;
  61. }
  62. };
  63. }
  64. }
复制代码

5.MainActivity的代码:

  1. public class MainActivity extends AppCompatActivity implements View.OnClickListener{
  2. public static final String TAG = MainActivity.class.getName();
  3. private ProgressBar download_progress;
  4. private TextView download_text;
  5. public static String basePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/okhttp";
  6. @Override
  7. protected void onCreate(Bundle savedInstanceState) {
  8. super.onCreate(savedInstanceState);
  9. setContentView(R.layout.activity_main);
  10. download_progress = (ProgressBar) findViewById(R.id.download_progress);
  11. download_text = (TextView) findViewById(R.id.download_text);
  12. findViewById(R.id.ok_download).setOnClickListener(this);
  13. }
  14. @Override
  15. public void onClick(View view) {
  16. switch (view.getId()){
  17. case R.id.ok_download:
  18. String url = "http://192.168.0.104:8080/OkHttpServer/download/2.jpg";
  19. final String fileName = url.split("/")[url.split("/").length - 1];
  20. Log.i(TAG, "fileName==" + fileName);
  21. OkHttpUtil.downloadFile(url, new ProgressListener() {
  22. @Override
  23. public void onProgress(long currentBytes, long contentLength, boolean done) {
  24. Log.i(TAG, "currentBytes==" + currentBytes + "==contentLength==" + contentLength + "==done==" + done);
  25. int progress = (int) (currentBytes * 100 / contentLength);
  26. download_progress.setProgress(progress);
  27. download_text.setText(progress + "%");
  28. }
  29. }, new Callback() {
  30. @Override
  31. public void onFailure(Call call, IOException e) {
  32. }
  33. @Override
  34. public void onResponse(Call call, Response response) throws IOException {
  35. if (response != null) {
  36. InputStream is = response.body().byteStream();
  37. FileOutputStream fos = new FileOutputStream(new File(basePath + "/" + fileName));
  38. int len = 0;
  39. byte[] buffer = new byte[2048];
  40. while (-1 != (len = is.read(buffer))) {
  41. fos.write(buffer, 0, len);
  42. }
  43. fos.flush();
  44. fos.close();
  45. is.close();
  46. }
  47. }
  48. });
  49. break;
  50. }
  51. }
  52. }
复制代码

6.最后不要忘了添加权限:

  1. <uses-permission android:name="android.permission.INTERNET"/>
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  3. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
复制代码

这里写图片描述

文件下载目录

源码下载

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。



回复

使用道具 举报

关闭

站长推荐上一条 /1 下一条