package com.yutou.tools.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class BiliBiliLiveTools {
    public static String getLiveUserName(String cid){
        try {
            HttpsURLConnection connection= (HttpsURLConnection) new URL("https://api.live.bilibili.com/xlive/web-room/v1/index/getInfoByRoom?room_id="+cid).openConnection();
            connection.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36");
            BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String tmp;
            StringBuilder str= new StringBuilder();
            while ((tmp=reader.readLine())!=null){
                str.append(tmp);
            }
            JSONObject json= JSON.parseObject(str.toString());
            reader.close();
            return json.getJSONObject("data").getJSONObject("anchor_info").getJSONObject("base_info").getString("uname");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
