通过循环遍历url下载多个视频并合并在一起,合并多个输入流到一个输出流:
package com.xw.smart.market.product.rest.controller;
import com.xw.smart.market.product.common.utils.DateUtils;
import com.xw.smart.market.product.service.MqService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
*/
@Slf4j
@RestController
@RequestMapping("mq")
public class MqController {
@Autowired
private MqService mqService;
/**
* 合并文件流
*/
@ApiOperation("合并文件流")
@GetMapping("/down")
public void down(HttpServletResponse response) throws Exception {
//前置url
String urlStart = "https:/26/f53b02eb387702304506466117/v.f146750_";
//后置url
String urlEnd = ".ts?t=6328eea1&us=AGe942c700_oiGmVVazEz&time=1663583714248";
// String urlVideo = urlStart + num + urlEnd;
String currentDateTime = DateUtils.getCurrentDateStr();
String spName = currentDateTime + "-8月18日-导师研究课-《鲁滨逊漂流记》整本书教学" + ".ts";
// 所以使用win系统的自行更换
String bdPath = "D:\soft\" + spName; // 保存到服务器的地址
boolean downVideo = downVideo(urlStart, urlEnd, bdPath);
}
/**
* 下载视频
*
* @param downloadPath 视频保存地址
*/
public static boolean downVideo(String urlStart, String urlEnd, String downloadPath) {
int num = 1;
HttpURLConnection connection = null;
InputStream inputStream = null;
boolean re = false;
try {
//创建合并流对象
FileOutputStream fos = new FileOutputStream(downloadPath);
for (int i = 1; i < 3000; i++) {
URL url = new URL(urlStart + i + urlEnd);
log.info(String.valueOf(i));
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Range", "bytes=0-");
connection.connect();
//校验访问状态,用来判断是否继续循环
if (connection.getResponseCode() / 100 != 2) {
System.out.println("连接中断,数据已传输完成。");
fos.close();
return re;
}
inputStream = connection.getInputStream();
//一次读取一个字节数组
byte[] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
//写
fos.write(bytes, 0, len);
}
}
fos.close();
} catch (MalformedURLException e) {
e.printStackTrace();
re = false;
return re;
} catch (IOException e) {
e.printStackTrace();
re = false;
return re;
} finally {
try {
connection.disconnect();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return re;
}
}