个人知识碎片的体系化理解与整理,缓慢更新,理解不到位与错漏之处望见谅与指正。
day04摘要思想:主要涉及hutool发送http请求,alibaba fastjson处理json数据,LinkedHashMap的使用,文件流的创建与保存等后台常见应用场景;需要调用b站的对外接口获取实际数据
开发环境:Intellij IDEA 2017.2.6
1.相关工具类Maven引入
hutool发送http请求工具类:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.1</version>
</dependency>
alibaba fastjson处理json工具类:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
所有的maven引入可直接在https://mvnrepository.com/artifact进行搜索获取当前最新版本;
2.基础请求地址
需要先获取该av号/bv号所指向视频资源的实际cid,再根据其cid获取实际下载地址:
//获取cid地址
private static final String cidUrl = "https://api.bilibili.com/x/web-interface/view";
//获取下载地址
private static final String downloadUrl = "https://api.bilibili.com/x/player/playurl";
//下载请求头
private static final String refererUrl = "https://www.bilibili.com/video/$";
3.获取视频实际分P的cid
av号请求地址示例:https://api.bilibili.com/x/web-interface/view?aid=380160
bv号请求地址示例:https://api.bilibili.com/x/web-interface/view?bvid=BV1Tx411P7fo
实际返回json过长,此处仅截取部分核心数据:
{
"title": "【合集】Kanon 雪之少女【BDRip】【澄空】【1080P】",
"pages": [{
"cid": 2933938,
"page": 1,
"from": "vupload",
"part": "白銀の序曲(オーバーチュア)~overture~ (银白色的序曲~overture~)",
"duration": 1453,
"vid": "",
"weblink": "",
"dimension": {
"width": 0,
"height": 0,
"rotate": 0
}
}]
}
获取cid代码如下:
//获取cid与视频名称,根据pageSize从第一P开始获取,根据aid或bvid重载该方法
private LinkedHashMap<String,JSONObject> getCid(Long aid , int pageSize) {
if(pageSize < 1) {
throw new FrameworkException("分P数量至少为1!");
}
String responseBody = HttpRequest.get(cidUrl + "?aid=" + aid.toString()).timeout(20000).execute().body();
LinkedHashMap<String,JSONObject> resultMap = new LinkedHashMap<>();
JSONObject responseJson = JSONObject.parseObject(responseBody);
JSONObject responseData = responseJson.getJSONObject("data");
JSONObject titleObject = new JSONObject();
titleObject.put("title",responseData.getString("title"));
resultMap.put("0",titleObj