OKHTTP的分批下载 和断点上传

本文介绍了如何使用OKHTTP库进行分批下载和断点上传操作,涉及Activity、工具类以及MVC框架的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@[toc] 分批 下载 断点上传

Activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/but_dwl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下载" />

    <Button
        android:id="@+id/but_upl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="上传" />

    <ProgressBar
        android:id="@+id/progress_bar"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100" />

</LinearLayout>

activity


package com.example.load;

import android.Manifest;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.example.load.listener.MyProgressListener;
import com.example.load.model.LoadModel;
import com.example.load.model.LoadModelImpl;

public class MainActivity extends AppCompatActivity {
    private Button butDwl;
    private Button butUpl;
    private ProgressBar progressBar;

    private String path = "http://uvideo.spriteapp.cn/video/2019/1103/5dbe410db5f46_wpd.mp4";

    private String sd_path = "/storage/emulated/0/Movies/rabbit1.mp4";

    private String hfs_path = "http://169.254.3.179/hfs/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
        }

        butDwl = (Button) findViewById(R.id.but_dwl);
        butUpl = (Button) findViewById(R.id.but_upl);
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);

        final LoadModel loadModel = new LoadModelImpl();

        butDwl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadModel.dwl(path, new MyProgressListener() {
                    @Override
                    public void onSuccess(int progress) {
                        progressBar.setProgress(progress);
                    }

                    @Override
                    public void onDefeat(String string) {

                    }
                });
            }
        });


        butUpl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadModel.upl(hfs_path, sd_path, "asd.mp4", "media/mp4", new MyProgressListener() {
                    @Override
                    public void onSuccess(int progress) {
                        progressBar.setProgress(progress);
                    }

                    @Override
                    public void onDefeat(String string) {
                        Toast.makeText(MainActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });


    }
}

工具类

package com.example.load.utils;

import android.os.Handler;
import android.support.annotation.Nullable;

import com.example.load.listener.MyProgressListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

public class OkHttpUtils {

    private OkHttpClient client;
    private Handler handler = new Handler();
    private int number;
    private int count = 0;
    private long length;
    private File file;
    private int flag = 0;

    private OkHttpUtils() {

        client = new OkHttpClient.Builder()
                .readTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .build();

    }

    private static OkHttpUtils okHttpUtils = null;

    public static OkHttpUtils getInstance() {
        okHttpUtils = new OkHttpUtils();
        return okHttpUtils;
    }


    public void DownLoad(final String path, final MyProgressListener listener) {
        Request request = new Request.Builder()
                .url(path)
                .get()
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                final String message = e.getMessage();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        listener.onDefeat(message);
                    }
                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                length = response.body().contentLength();
                number = (int) (length / 3);

                getPart(path, listener);

            }
        });

    }

    public void getPart(String path, final MyProgressListener listener) {

        //第一部分
        Request request1 = new Request.Builder()
                .get()
                .url(path)
                .header("Range", "bytes=" + 0 + "-" + number)
                .build();


        client.newCall(request1).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String message = e.getMessage();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = response.body().byteStream();
                RandomAccessFile accessFile = new RandomAccessFile("/storage/emulated/0/Movies/rabbit1.mp4", "rw");
                accessFile.seek(0);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    accessFile.write(bytes, 0, len);
                    count += len;
                    final int progress = (int) (count * 100 / length);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onSuccess(progress);
                        }
                    });
                }
            }
        });

        //第二部分
        Request request2 = new Request.Builder()
                .get()
                .url(path)
                .header("Range", "bytes=" + number + "-" + number * 2)
                .build();


        client.newCall(request2).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String message = e.getMessage();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = response.body().byteStream();
                RandomAccessFile accessFile = new RandomAccessFile("/storage/emulated/0/Movies/rabbit1.mp4", "rw");
                accessFile.seek(number);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    accessFile.write(bytes, 0, len);
                    count += len;
                    final int progress = (int) (count * 100 / length);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onSuccess(progress);
                        }
                    });
                }
            }
        });

        //第三部分
        Request request3 = new Request.Builder()
                .get()
                .url(path)
                .header("Range", "bytes=" + number * 2 + "-" + length)
                .build();


        client.newCall(request3).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String message = e.getMessage();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = response.body().byteStream();
                RandomAccessFile accessFile = new RandomAccessFile("/storage/emulated/0/Movies/rabbit1.mp4", "rw");
                accessFile.seek(number * 2);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    accessFile.write(bytes, 0, len);
                    count += len;
                    final int progress = (int) (count * 100 / length);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onSuccess(progress);
                        }
                    });
                }
            }
        });

    }

    public void UpLoad(String path, final String sd_path, String servername, String type, final MyProgressListener listener) {

        file = new File(sd_path);

//        RequestBody body = RequestBody.create(MediaType.parse("media/mp4"), file);
        RequestBody requestBody = new RequestBody() {
            @Nullable
            @Override
            public MediaType contentType() {
                return MediaType.parse("media/mp4");
            }

            @Override
            public long contentLength() throws IOException {
                return file.length();
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
                accessFile.seek(0);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = accessFile.read(bytes)) != -1) {
                    sink.write(bytes, 0, len);
                    count += len;

                    final int progress = (int) (count * 100 / (file.length()));

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onSuccess(progress);
                        }
                    });
                }
            }
        };


        MultipartBody build = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", servername, requestBody)
                .build();


        final Request request = new Request.Builder()
                .post(build)
                .url(path)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                final String message = e.getMessage();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        listener.onDefeat(message);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                boolean successful = response.isSuccessful();
                if (successful) {
                } else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onDefeat("失败");
                        }
                    });
                }


            }
        });

    }


}

mvc 框架

package com.example.load.model;

import com.example.load.listener.MyProgressListener;

public interface LoadModel {
    void dwl(String path, MyProgressListener listener);
    void upl(String path,String sd_path,String serverS,String type,MyProgressListener listener);
}

package com.example.load.model;

import com.example.load.listener.MyProgressListener;
import com.example.load.utils.OkHttpUtils;

public class LoadModelImpl implements LoadModel {
    @Override
    public void dwl(String path, MyProgressListener listener) {
        OkHttpUtils.getInstance().DownLoad(path, listener);
    }

    @Override
    public void upl(String path, String sd_path, String serverS, String type, MyProgressListener listener) {
        OkHttpUtils.getInstance().UpLoad(path, sd_path, serverS, type, listener);
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值