HttpURLConnection网络资源下载断点续传
相关方法
connection.setRequestMethod("GET");//设置请求方法
connection.setConnectTimeout(8000);//设置请求连接超时时间
connection.setRequestProperty("Range","bytes="+start+"-"+end);//设置请求数据范围 start-end 范围之间
connection.setDoInput(true);//设置可读
connection.setDoOutput(true);//设置可写
connection.getContentLength();//获取请求网址资源数据大小 返回值为int
首先 我们在下载之前需要先获取到网络资源的总大小
所以我们先开一条线程,获取资源总大小,用来设置进度条的总大小
我代码中写的是同时下载两个网络资源 所以有个if判断
public void getUrlSize(final String string, final int i){
new Thread(new Runnable() {
@Override
public void run() {
URL url= null;
try {
url = new URL(string);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
if(i==1){
end=connection.getContentLength();
Message obtain = Message.obtain();
obtain.what=2;
handler.sendMessage(obtain);
}else {
end2=connection.getContentLength();
Message obtain = Message.obtain();
obtain.what=4;
handler.sendMessage(obtain);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
然后我们写下载线程
class MyThread extends Thread{
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void run() {
super.run();
try {
URL url=new URL("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setRequestProperty("Range","bytes="+start+"-"+end);
connection.setDoInput(true);
connection.setDoOutput(true);
Log.d("####", "run: 下载总总量111"+end);
String path=Environment.getExternalStorageDirectory().getPath()+"/迷人的diao.mp4";
RandomAccessFile file=new RandomAccessFile(path,"rw");
file.seek(sum); //设置标记 如果暂停 则从已下载完的数据点开始写入
InputStream inputStream = null;
if(connection.getResponseCode()==206){
Log.d("####", "run: 进入");
inputStream = connection.getInputStream();
byte[] bytes=new byte[1024];
int len = 0;
while((len=inputStream.read(bytes))!=-1){
file.write(bytes,0,len);
sum+=len;
Log.d("####", "run: 下载量"+sum);
Message obtain1 = Message.obtain();
obtain1.what=1;
handler.sendMessage(obtain1);
if(sum==end){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
}
});
isDown=false;
}
if(!isDown){
start=sum;
break;
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上代码中的handler用于更新进度条
isDown用于判断是否暂停
整体代码如下:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ProgressBar bar;
ProgressBar bar2;
int start=0;
int end=0;
int sum=0;
boolean isDown=true;
int end2=0;
int start2=0;
int sum2=0;
boolean isDown2=true;
TextView textView;
TextView textView2;
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
bar.setProgress((int) Math.floor(sum/1000));
if(sum==end){
textView.setText("下载完成");
}
break;
case 2:
bar.setMax((int) Math.floor(end/1000));
Log.d("####", "run: 进度条设置");
break;
case 3:
bar2.setProgress((int) Math.floor(sum2/1000));
if(sum2==end2){
textView2.setText("下载完成");
}
break;
case 4:
bar2.setMax((int) Math.floor(end2/1000));
Log.d("####", "run: 进度条设置");
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bar = findViewById(R.id.jindutiao);
bar2 = findViewById(R.id.jindutiao2);
textView=findViewById(R.id.zhuangtai);
textView2=findViewById(R.id.zhuangtai2);
findViewById(R.id.startDownload).setOnClickListener(this);
findViewById(R.id.startDownload2).setOnClickListener(this);
findViewById(R.id.stopDownload).setOnClickListener(this);
findViewById(R.id.stopDownload2).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.startDownload:
isDown=true;
Toast.makeText(MainActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
getUrlSize("http://qiubai-video.qiushibaike.com/VGU6K0T3CDU6N7JJ_3g.mp4",1);
new MyThread().start();
break;
case R.id.stopDownload:
isDown=false;
Toast.makeText(MainActivity.this, "已暂停", Toast.LENGTH_SHORT).show();
break;
case R.id.startDownload2:
isDown2=true;
Toast.makeText(MainActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
getUrlSize("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4",2);
new MyThread2().start();
break;
case R.id.stopDownload2:
isDown2=false;
Toast.makeText(MainActivity.this, "已暂停", Toast.LENGTH_SHORT).show();
break;
}
}
public void getUrlSize(final String string, final int i){
new Thread(new Runnable() {
@Override
public void run() {
URL url= null;
try {
url = new URL(string);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
if(i==1){
end=connection.getContentLength();
Message obtain = Message.obtain();
obtain.what=2;
handler.sendMessage(obtain);
}else {
end2=connection.getContentLength();
Message obtain = Message.obtain();
obtain.what=4;
handler.sendMessage(obtain);
}
Log.d("####", "run: 下载总总量2828282823828----"+end);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
class MyThread extends Thread{
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void run() {
super.run();
try {
URL url=new URL("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setRequestProperty("Range","bytes="+start+"-"+end);
connection.setDoInput(true);
connection.setDoOutput(true);
Log.d("####", "run: 下载总总量111"+end);
String path=Environment.getExternalStorageDirectory().getPath()+"/迷人的diao.mp4";
RandomAccessFile file=new RandomAccessFile(path,"rw");
Log.d("####", "run: 创建文件");
file.seek(sum);
Log.d("####", "run: 设置下标");
InputStream inputStream = null;
if(connection.getResponseCode()==206){
Log.d("####", "run: 进入");
inputStream = connection.getInputStream();
byte[] bytes=new byte[1024];
int len = 0;
while((len=inputStream.read(bytes))!=-1){
file.write(bytes,0,len);
sum+=len;
Log.d("####", "run: 下载量"+sum);
Message obtain1 = Message.obtain();
obtain1.what=1;
handler.sendMessage(obtain1);
if(sum==end){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
}
});
isDown=false;
}
if(!isDown){
start=sum;
break;
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class MyThread2 extends Thread{
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void run() {
super.run();
try {
URL url=new URL("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setRequestProperty("Range","bytes="+start2+"-"+end2);
connection.setDoInput(true);
connection.setDoOutput(true);
String path=Environment.getExternalStorageDirectory().getPath()+"/迷人的diao2.mp4";
RandomAccessFile file=new RandomAccessFile(path,"rw");
file.seek(sum2);
InputStream inputStream = null;
if(connection.getResponseCode()==206){
inputStream = connection.getInputStream();
byte[] bytes=new byte[1024];
int len = 0;
while((len=inputStream.read(bytes))!=-1){
file.write(bytes,0,len);
sum2+=len;
Message obtain1 = Message.obtain();
obtain1.what=3;
handler.sendMessage(obtain1);
if(sum2==end2){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
}
});
isDown2=false;
}
if(!isDown2){
start2=sum2;
break;
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以上代码中有两条数据请求 部分可省略;