分为三个步骤
收集<audio>标签
将标签数据转换为JSON格式
下载到本地目录
package com.zb.test;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.compress.utils.Lists;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DownloadExample {
public static void main(String[] args) throws Exception {
//1 收集<audio>标签
String html = "<audio title=\"平凡的咖啡音乐\" src=\"https://audio.xmcdn.com/storages/67dd-audiofreehighqps/34/1D/GKwRIRwHlEXtAda-PgHrZIsc.m4a\"></audio>";
//转换为JSON格式
List<JSONObject> jsonObjects = ConvertToJSONFormat(html);
//下载到本地
for (JSONObject jsonObject : jsonObjects) {
download(jsonObject.getString("src"), jsonObject.getString("title"));
}
}
public static List<JSONObject> ConvertToJSONFormat(String html) throws Exception {
String[] split = html.split("\\n");
List<JSONObject> jsonObjects = Lists.newArrayList();
for (String s : split) {
// Remove all backslashes
s = s.replace("\\", "");
// Extract attributes from audio element
String title = s.substring(s.indexOf("title=\"") + 7, s.indexOf("\" src"));
String src = s.substring(s.indexOf("src=\"") + 5, s.indexOf("\"></audio"));
// Create JSON object with attributes
JSONObject json = new JSONObject();
json.put("title", title);
json.put("src", extractLink(src));// 提取link
jsonObjects.add(json);
}
return jsonObjects;
}
public static String extractLink(String input) {
// 使用正则表达式匹配字符串
Pattern pattern = Pattern.compile("jt=(.*)");
Matcher matcher = pattern.matcher(input);
// 如果匹配成功,则输出结果
String result = null;
if (matcher.find()) {
result = matcher.group(1);
}
return result;
}
public static void download(String urlString, String filename) throws Exception {
String directory = "/Users/kafeih/Downloads";
String extension = ".m4a";
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
Path file = Paths.get(directory, filename + extension);
FileOutputStream outputStream = new FileOutputStream(file.toFile());
byte[] buffer = new byte[4096];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
System.out.println("Download complete!");
}
}