java实现B站自动发送弹幕
一、数据准备
发送的数据可以从一些免费的API网站获取。如果嫌麻烦可以自己准备好数据放入List集合中,发送弹幕时依次遍历集合取其中的
内容即可。这里使用了一个第三方的API
public static String getContent() {
String url = "https://api.***************";//一个第三方的API数据获取地址,手动打码
String content = "";
Connection.Response response = null;
try {
//发送请求,获取数据
response = Jsoup.connect(url).ignoreContentType(true).timeout(5000).execute();
} catch (IOException e) {
System.out.println("数据请求失败!");
}
try {
RootSource value = mapper.readValue(response.body(), RootSource.class);
//返回的数据为json格式,随机数据内容在content中
content = value.getData().getContent();
//哔站直播弹幕内容控制在20个字符内,这里对请求获得的数据进行适当切割
//否则发送不出去
content=content.length()>20?content.substring(0,20):content;
} catch (JsonProcessingException e) {
System.out.println("解析数据失败!");
}
return content;
}
二、控制发送弹幕房间、弹幕数量、发送间隔时间
房间id获取方式
Scanner scanner = new Scanner(System.in);
System.out.print("请输入up房间ID:");
String room_id = scanner.next();
System.out.print("请输入要发送的弹幕数量:");
int count = scanner.nextInt();
System.out.print("请输入要发送弹幕的时间间隔(单位:ms):");
int time = scanner.nextInt();
System.out.println("房间ID:"+room_id+"\t弹幕数量:"+count+"\t时间间隔:"+time);
三、请求头信息设置
-
请求参数获取
-
请求头参数设置
//请求参数设置
Map<String, String> data = new HashMap<>();
data.put("bubble", "0");
data.put("color", "16777215");//设置弹幕字体颜色
data.put("mode", "1");
data.put("fontsize", "25");//设置弹幕字体大小
data.put("rnd", "********");
data.put("roomid", room_id);//设置主播的房间号
data.put("csrf", "c******************d9");
data.put("csrf_token", "c3d******************c9a18d9");
//请求头参数设置
Map<String, String> headers = new HashMap<>();
headers.put("referer", "https://live.bilibili.com/*************************");
headers.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36 Edg/103.0.1264.37");
headers.put("cookie", "....");//cookie信息这里省略
四、后台自动发送数据
String send = "https://api.live.bilibili.com/msg/send";//这里是bili发送弹幕的请求链接,请求方式为post
//循环发送数据
for (int i = 0; i < count; i++) {
//msg就是要发送的弹幕,将第一步获取的数据放入请求参数的map中
data.put("msg", getContent());
try {
Connection.Response response = Jsoup.connect(send)//获取链接对象
.timeout(5000)//设置超时时间
.headers(headers).data(data)//将请求参数、请求头放入请求中
.method(Connection.Method.POST)//设置请求方式为post请求
.execute();//发送弹幕
} catch (IOException e) {
System.out.println("发送失败");
}
System.out.println(data.get("msg"));
System.out.println("第" + (i + 1) + "条弹幕发送成功!");
Thread.sleep(time);//设置弹幕发送时间间隔
}
五、效果展示,顺利成为高能榜!