断点下载
思路步骤:需要进行两次请求:
1.获取文件的总大小
2.添加请求头Range:bytes=?1-?2 (?1从什么位置/大小开始下载 ?2文件总大小)
package com.example.app_random_2;
import android.Manifest;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private String[] permission = {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
};
private ProgressBar bar;
private Button bt;
private OkHttpClient client;
private long sumlength = 0;
private String path = "/sdcard/DCIM/abc.mp4";
private long start = 0;
private String url = "http://uvideo.spriteapp.cn/video/2019/0512/56488d0a-7465-11e9-b91b-1866daeb0df1_wpd.mp4";
private int count;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestPermissions(permission,100);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
bar = (ProgressBar) findViewById(R.id.bar);
bt = (Button) findViewById(R.id.bt);
bt.setOnClickListener(this);
client = new OkHttpClient.Builder().build();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt:
// 第一次请求获取 文件的大小
final Request request = new Request.Builder()
.url(url)
.get()
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
sumlength = response.body().contentLength();
}
});
// 第二次请求添加请求头 Range:bytes=?-?
File file = new File(path);
if (file.exists()){
start = file.length();
}else {
start = 0;
}
Request request1 = new Request.Builder()
.url(url)
.get()
.header("Rang", "bytes=" + start + "-" + sumlength)
.build();
client.newCall(request1).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream inputStream = response.body().byteStream();
FileOutputStream fileOutputStream = new FileOutputStream(path, true); // 追加
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,len);
count += len;
handler.post(new Runnable() {
@Override
public void run() {
bar.setProgress((int) (count*100/sumlength));
}
});
}
}
});
break;
}
}
}