- package org.load.music;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.util.Scanner;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import org.w3c.dom.Document;
- import org.w3c.dom.Element;
- import org.w3c.dom.NodeList;
- // 命令行下载百度音乐
- public class BaiduMusic {
- public static void main(String[] args) {
- String musicName = null;
- String next = null;
- while(true) {
- System.out.println("输入名称:(输入exit停止输入)");
- musicName = new Scanner(System.in).next();
- if("exit".equalsIgnoreCase(musicName)) {
- break;
- }
- new Thread(new DownloadThread(musicName)).start();
- }
- }
- }
- class DownloadThread implements Runnable {
- private static final String URL = "http://box.zhangmen.baidu.com/x?op=12&count=1&title="; // 请求地址+音乐名称+$$(+歌手+$$$)
- private String musicName = null;
- private String musicType = ".mp3";
- public DownloadThread(String musicName) {
- this.musicName = musicName;
- }
- @Override
- public void run() {
- try {
- this.download();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public void download() throws Exception {
- String path = this.parseMusic();
- URL url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setConnectTimeout(5*1000); // 5s超时
- InputStream in = conn.getInputStream();
- OutputStream out = new FileOutputStream("E:\\\\" + this.musicName + this.musicType);
- byte[] by = new byte[512];
- int len = 0;
- while(-1!=(len=in.read(by))) {
- out.write(by, 0, len);
- }
- out.flush();
- in.close();
- out.close();
- }
- public String parseMusic() throws Exception {
- // 解析url
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document doc = builder.parse(URL + this.musicName + "$$");
- NodeList encodes = doc.getElementsByTagName("encode"); // 得到encode节点
- Element encode = (Element) encodes.item(0); // 取得第一个encode节点
- String musicUrl = encode.getChildNodes().item(0).getNodeValue(); // 取得encode节点的TextNode
- String url = musicUrl.substring(0, musicUrl.lastIndexOf('/')) + "/"; // 解析出url
- // 解析名称
- NodeList decodes = doc.getElementsByTagName("decode"); // 取得decode节点
- Element decode = (Element) decodes.item(0); // 取得第一个decode节点
- String musicName = decode.getFirstChild().getNodeValue(); // 解析出音乐名
- this.musicType = musicName.substring(musicName.indexOf('.'), musicName.indexOf('?')); // 解析出音乐类型
- return url + musicName;
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/0701201511509.html
来源: http://www.codesnippet.cn/detail/0701201511509.html