批量下载歌曲

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cx.client.utils.XHttpQueryUtils;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.io.Files;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Before;
import org.junit.Test;

import java.io.*;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FunTest {
    private HttpClient httpClient;
    private File headerFile = new File(XHttpQueryUtils.class.getResource("/assert/base-form-header.txt").getFile());

    @Before
    public void before() {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(60000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    @Test
    public void fun() throws IOException, URISyntaxException {
        List<String> htmlStrings = Files.readLines(new File(getClass().getResource("/source.html").getFile()), Charsets.UTF_8);
        String join = Joiner.on("").join(htmlStrings);
        Document parse = Jsoup.parse(join);
        Elements lis = parse.select("ul>li");
        for (Element element : lis) {
            String attr = element.attr("data-id");
            List<String> strings = Splitter.on("|").omitEmptyStrings().splitToList(attr);
            String token = strings.get(0);
//            http://www.9ku.com/play/15870.htm
//            http://ar.h5.rh01.sycdn.kuwo.cn/resource/n1/73/93/998018280.mp3
            String reqUrl = getDownloadUrl(token);
            HttpGet get = new HttpGet(reqUrl);
            List<String> list = Files.readLines(headerFile, Charsets.UTF_8);
            for (String s : list) {
                List<String> toList = Splitter.on(":").splitToList(s);
                get.setHeader(toList.get(0), toList.get(1));
            }
            // 发送数据请求
            HttpResponse response = httpClient.execute(get);
            String responseStr = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
            //自定义处理返回结果
            String x = unicodeToCn(responseStr);
            JSONObject jsonObject = JSON.parseObject(x);
            Object mname = jsonObject.get("mname");
            Object wma = jsonObject.get("wma");
            File file = new File("C:\\Users\\chengxiao1\\Desktop\\音乐", mname.toString() + ".mp3");
            if (!file.exists()) {
                boolean newFile = file.createNewFile();
            }
            get.setURI(new URI(wma.toString()));
            HttpResponse response1 = httpClient.execute(get);
            HttpEntity httpEntity = response1.getEntity();
            InputStream is = httpEntity.getContent();
            // 根据InputStream 下载文件
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int r;
            while ((r = is.read(buffer)) > 0) {
                output.write(buffer, 0, r);
            }
            FileOutputStream fos = new FileOutputStream(file);
            output.writeTo(fos);
            output.flush();
            output.close();
            fos.close();
            EntityUtils.consume(httpEntity);
        }
    }

    private String getDownloadUrl(String token) {
        BigDecimal origin = new BigDecimal(token);
        BigDecimal fix = new BigDecimal("1000");
        BigDecimal bigDecimal = origin.divide(fix, 0, BigDecimal.ROUND_FLOOR);
        int x = bigDecimal.intValue() + 1;
        return "http://www.9ku.com/html/playjs/" + x + "/" + token + ".js";
    }

    private String unicodeToCn(String str) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");
        }
        String s = str.replaceAll("\\\\/", "/");
        return s.substring(2, s.length() - 1);
    }

}

你可能感兴趣的:(随笔)