上一篇 java下载m3u8视频,解密并合并ts(二)——获取m3u8链接
编写代码
加载jar包
由于java不支持AES/CBC/PKCS7Padding模式解密,所以我们要借助第一篇下载好的jar包
当类加载时,通过静态代码块加载
/**
*
* 解决java不支持AES/CBC/PKCS7Padding模式解密
*
*/
static {
Security.addProvider(new BouncyCastleProvider());
}
所需类字段
//要下载的m3u8链接
private final String DOWNLOADURL;
//线程数
private int threadCount = 1;
//重试次数
private int retryCount = 30;
//链接连接超时时间(单位:毫秒)
private long timeoutMillisecond = 1000L;
//合并后的文件存储目录
private String dir;
//合并后的视频文件名称
private String fileName;
//已完成ts片段个数
private int finishedCount = 0;
//解密算法名称
private String method;
//密钥
private String key = "";
//所有ts片段下载链接
private Set<String> tsSet = new LinkedHashSet<>();
//解密后的片段
private Set<File> finishedFiles = new ConcurrentSkipListSet<>(Comparator.comparingInt(o -> Integer.parseInt(o.getName().replace(".xyz", ""))));
//已经下载的文件大小
private BigDecimal downloadBytes = new BigDecimal(0);
获取链接内容
模拟HTTP请求,获取链接相应内容
/**
* 模拟http请求获取内容
*
* @param urls http链接
* @return 内容
*/
private StringBuilder getUrlContent(String urls) {
int count = 1;
HttpURLConnection httpURLConnection = null;
StringBuilder content = new StringBuilder();
while (count <= retryCount) {
try {
URL url = new URL(urls);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout((int) timeoutMillisecond);
httpURLConnection.setReadTimeout((int) timeoutMillisecond);
httpURLConnection.setUseCaches(false);
httpURLConnection.setDoInput(true);
String line;
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = bufferedReader.readLine()) != null)
content.append(line).append("\n");
bufferedReader.close();
inputStream.close();
System.out.println(content);
break;
} catch (Exception e) {
// System.out.println("第" + count + "获取链接重试!\t" + urls);
count++;
// e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
}
if (count > retryCount)
throw new M3u8Exception("连接超时!");
return content;
}
判断是否需要解密
首先将m3u8链接内容通过getUrlContent方法获取到,然后解析,如果内容含有#EXT-X-KEY标签,则说明这个链接是需要进行ts文件解密的,然后通过下面的.m3u8的if语句获取含有密钥以及ts片段的链接。
如果含有#EXTINF,则说明这个链接就是含有ts视频片段的链接,没有第二个m3u8链接了。
之后我们要获取密钥的getKey方法,即时不需要密钥。并把ts片段加进set集合,即tsSet字段。