首页 > 编程语言 >bilibili视频解析—Java

bilibili视频解析—Java

时间:2023-09-29 13:11:19浏览次数:39  
标签:Java String url void private bilibili new folder 解析

public class Bilibili {
    private static String url, videoUrl, audioUrl, saveName;
    private boolean type;


    Bilibili(String saveName) {
        this.saveName = saveName;
    }

    public static void main(String[] args) {
        String url = "https://www.bilibili.com/video/BV1wd4y1w7kK/?spm_id_from=333.337.search-card.all.click&vd_source=29e334761a3a467100b2c30e4b85aab1";
        new Bilibili("payphone").analyse(url)
                .audio("").download().video("").download();

//        audioUrl = "https://upos-sz-mirror08c.bilivideo.com/upgcxcode/47/52/1047445247/1047445247_nb3-1-30280.m4s?e=ig8euxZM2rNcNbdlhoNvNC8BqJIzNbfqXBvEqxTEto8BTrNvN0GvT90W5JZMkX_YN0MvXg8gNEV4NC8xNEV4N03eN0B5tZlqNxTEto8BTrNvNeZVuJ10Kj_g2UB02J0mN0B5tZlqNCNEto8BTrNvNC7MTX502C8f2jmMQJ6mqF2fka1mqx6gqj0eN0B599M=&uipk=5&nbs=1&deadline=1692127574&gen=playurlv2&os=08cbv&oi=2059574121&trid=4c3d337b3a7a466c81239501786ed71au&mid=0&platform=pc&upsig=b85a234388e3266e97def2c95d57468c&uparams=e,uipk,nbs,deadline,gen,os,oi,trid,mid,platform&bvc=vod&nettype=0&orderid=0,3&buvid=&build=0&agrr=0&bw=14239&logo=80000000";
//        new Bilibili().audio("What's_Up", "").download();
    }

    interface Promise {
        void resolve(String mes);

        void reject();
    }

    private void get(String url, Promise pro) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request.Builder builder = new Request.Builder();
        Request request = builder.get().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                pro.reject();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                assert response.body() != null;
                pro.resolve(response.body().string());
            }
        });
    }

    public Bilibili download() {
        try {
            OkHttpClient client = new OkHttpClient.Builder().build();
            Request request = new Request.Builder()
                    .header("Referer", "https://www.bilibili.com")
                    .url(url)
                    .build();
            Response response = client.newCall(request).execute();
            byte[] bytes = response.body().bytes();

            if (bytes.length > 0) {
                Files.write(filePath, bytes, StandardOpenOption.CREATE);
                System.out.println(response.message() + "-downloaded-" + url);
            } else {
                System.out.println(response.message() + "-failed-" + url);
                download();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    private Bilibili analyse(String url) {
        get(url, new Promise() {
            @Override
            public void resolve(String str) {
                Pattern pat = Pattern.compile("__playinfo__.*?</script>");
                Matcher matcher = pat.matcher(str);
                if (matcher.find()) {
                    String group = matcher.group();
                    int start = group.indexOf("{");
                    int end = group.lastIndexOf("}") + 1;
                    String result = group.substring(start, end);
                    JSONObject obj = new JSONObject(result);
                    videoUrl = (String) obj.getJSONObject("data").getJSONObject("dash").getJSONArray("video").getJSONObject(0).get("baseUrl");
                    audioUrl = (String) obj.getJSONObject("data").getJSONObject("dash").getJSONArray("audio").getJSONObject(2).getJSONArray("backupUrl").get(1);
                    System.out.println("get url");
                } else {
                    System.out.println("no match");
                }
            }

            @Override
            public void reject() {
                System.out.println("request error");
            }
        });

        while (videoUrl == null) Thread.onSpinWait();

        return this;
    }

    private String folder;
    private Path filePath;

    private Bilibili video(String folder) {
        this.url = videoUrl;
        this.type = true;
        pathVerify(folder);
        return this;
    }

    private Bilibili audio(String folder) {
        this.url = audioUrl;
        this.type = false;
        pathVerify(folder);
        return this;
    }

    private void pathVerify(String folder) {
        this.folder = folder;
        if ("".equals(folder))
            this.folder = new File("").getAbsolutePath();

        if (!this.folder.endsWith("/"))
            this.folder = this.folder + "/";

        Path folderPath = Paths.get(this.folder);
        if (!Files.exists(folderPath)) {
            try {
                Files.createDirectories(folderPath);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        filePath = Paths.get(folder + saveName + (type ? ".mp4" : ".mp3"));
        if (Files.exists(filePath, LinkOption.NOFOLLOW_LINKS))
            filePath.toFile().delete();
    }

}

 

标签:Java,String,url,void,private,bilibili,new,folder,解析
From: https://www.cnblogs.com/laremehpe/p/17736926.html

相关文章

  • 【中秋国庆不断更】XML在HarmonyOS中的生成,解析与转换(上)
    一、XML概述XML(可扩展标记语言)是一种用于描述数据的标记语言,旨在提供一种通用的方式来传输和存储数据,特别是Web应用程序中经常使用的数据。XML并不预定义标记。因此,XML更加灵活,并且可以适用于广泛的应用领域。XML文档由元素(element)、属性(attribute)和内容(content)组成。​......
  • java——mysql随笔
         索引简介:                                                                 1 ......
  • STM32CubeMX 生成的 Makefile 文件解析
    STM32CubeMX生成的Makefile文件解析Makefile的前置知识一个makefile是由一系列的规则(rule)组成的。一条完整的规则包括目标(target)、依赖(prerequistites)、方法(recipe):target...:prerequistites...recipe......依赖和方法不一定需要同......
  • 通过HTML和JavaScript实现随机抽取幸运员工
    需求描述:公司经常会要求IT部门做一个小功能给公司随机抽取员工<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0"><t......
  • 结对项目:Java实现自动生成小学四则运算题目
    结队项目软件工程所在班级队伍成员谢昊天(3121004672)林育鑫(3121004660)作业要求[要求](([个人项目-作业-计科21级12班-班级博客-博客园(cnblogs.com)](结对项目-作业-计科21级12班-班级博客-博客园(cnblogs.com))))作业目标实现一个自动生成......
  • 无涯教程-JavaScript - CONCATENATE函数
    描述CONCATENATE函数将两个或多个文本字符串连接为一个字符串。在Excel2016中,CONCATENATE函数已被CONCAT函数替换。CONCATENATE函数仍可用于向后兼容。语法CONCATENATE(text1,[text2]...)争论Argument描述Required/Optionaltext1Thefirstitemtojoin.Theit......
  • 无涯教程-JavaScript - CONCAT函数
    描述Combinesthetextfrommultiplerangesand/orstrings,butitdoesn'tprovidethedelimiterorIgnoreEmptyarguments.Toincludedelimiters(suchasspacingorampersands(&)betweenthetextsyouwanttocombineandtoremoveemptyarguments......
  • OWASP Top 10漏洞解析(2)- A2:Cryptographic Failures 加密机制失效
    作者:gentle_zhou原文链接:<https://bbs.huaweicloud.com/blogs/405125>Web应用程序安全一直是一个重要的话题,它不但关系到网络用户的隐私,财产,而且关系着用户对程序的新人。随着Web应用程序功能持续增加,复杂性不断提高,这些程序也面临着越来越多的安全威胁和挑战。为了帮助这些应用程......
  • Java内存分析工具实践之Spark客户端线程死锁
    ......
  • 无涯教程-JavaScript - CODE函数
    描述CODE函数返回文本字符串中第一个字符的数字代码。返回的代码对应于Windows系统的ANSI字符集。语法CODE(text)争论Argument描述Required/OptionalTextThetextforwhichyouwantthecodeofthefirstcharacter.Required适用性Excel2007,Excel2010,Excel......