Java调用腾讯会议Api示例

最近疫情严重,公司准备出一个在线视频会议功能,需要调用腾讯会议的API,经过查看腾讯的api文档和与腾讯技术人员交流,终于能成功调用Api接口了!

腾讯会议官方API:https://cloud.tencent.com/document/product/1095/42407

首先第一步需要申请腾讯 API 接入

申请好了以后,会邮件发给你APPID,SecretId,SecretKey三个参数。

我们以创建会议为例,步骤如下:

一、生成body参数

        //body参数
        String req_body="{\n" +
                "\t\"userid\": \"tester\",\n" +
                "\t\"instanceid\": 1,\n" +
                "\t\"subject\": \"tester's meeting\",\n" +
                "\t\"type\": 0,\n" +
                "\t\"hosts\": [{\n" +
                "\t\t\"userid\": \"tester\"\n" +
                "\t}],\n" +
                "\t\"start_time\": \""+createTime+"\",\n" +
                "\t\"end_time\": \""+createtomorrow+" \",\n" +
                "\t\"settings \": {\n" +
                "\t\t\"mute_enable_join \": true,\n" +
                "\t\t\"allow_unmute_self \": false,\n" +
                "\t\t\"mute_all \": false,\n" +
                "\t\t\"host_video \": true,\n" +
                "\t\t\"participant_video \": false,\n" +
                "\t\t\"enable_record \": false,\n" +
                "\t\t\"play_ivr_on_leave\": false,\n" +
                "\t\t\"play_ivr_on_join\": false,\n" +
                "\t\t\"live_url\": false\n" +
                "\t}\n" +
                "}";

 二、生成签名

String num="";//随机数
String signature = sign(SecretId, SecretKey, "POST", num, createTime, uri, req_body);
        

 三、请求

 String code=doPost(url,Content_Type,SecretId,createTime,num,appId,signature,datas);

完整代码如下:

package com.jbox.common.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;

/**
 * @author huangting
 * @version 1.0
 * @date 17:43 2020/4/8
 */
public class TencentUtil {
    public static String createMeetings() throws IOException, InvalidKeyException, NoSuchAlgorithmException {
        String uri="/v1/meetings";
        String SecretId="";
        String SecretKey="";
        String appId="";
        String url="https://api.meeting.qq.com/v1/meetings";
        int num=617877739;
        Date today=  new  Date();
        Calendar c = Calendar.getInstance();
        c.setTime(new  Date());//今天
        c.add(Calendar.DAY_OF_MONTH,1);
        Date tomorrow=c.getTime();//这是明天
        int createTime = getSecondTimestamp(today);
        int createtomorrow = getSecondTimestamp(tomorrow);
        //body参数
        String req_body="{\n" +
                "\t\"userid\": \"tester\",\n" +
                "\t\"instanceid\": 1,\n" +
                "\t\"subject\": \"tester's meeting\",\n" +
                "\t\"type\": 0,\n" +
                "\t\"hosts\": [{\n" +
                "\t\t\"userid\": \"tester\"\n" +
                "\t}],\n" +
                "\t\"start_time\": \""+createTime+"\",\n" +
                "\t\"end_time\": \""+createtomorrow+" \",\n" +
                "\t\"settings \": {\n" +
                "\t\t\"mute_enable_join \": true,\n" +
                "\t\t\"allow_unmute_self \": false,\n" +
                "\t\t\"mute_all \": false,\n" +
                "\t\t\"host_video \": true,\n" +
                "\t\t\"participant_video \": false,\n" +
                "\t\t\"enable_record \": false,\n" +
                "\t\t\"play_ivr_on_leave\": false,\n" +
                "\t\t\"play_ivr_on_join\": false,\n" +
                "\t\t\"live_url\": false\n" +
                "\t}\n" +
                "}";
        //生成签名
        String signature = sign(SecretId, SecretKey, "POST", "617877739", String.valueOf(createTime), uri, req_body);
        System.out.println("我是签名:"+signature);
        String Content_Type="application/json";
        String datas = req_body;
        String code=doPost(url,Content_Type,SecretId,createTime,num,appId,signature,datas);
        System.out.println(code);
        return code;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, IOException {
        String code=createMeetings();
    }

    private static String doPost(String urlPath,String Content_Type,String SecretId,int createTime,int num,String appId,String signature,String datas) throws IOException {
        StringBuilder sub = new StringBuilder();
        // 建立连接
        try {
            URL url = new URL(urlPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置连接请求属性post
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 忽略缓存
            //conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("X-TC-Key", SecretId);
            conn.setRequestProperty("X-TC-Timestamp", String.valueOf(createTime));
            conn.setRequestProperty("X-TC-Nonce", String.valueOf(num));
            conn.setRequestProperty("AppId", appId);
            conn.setRequestProperty("X-TC-Signature", signature);
            System.out.println(signature);
            DataOutputStream out =new DataOutputStream(conn.getOutputStream());
            out.write(datas.getBytes());
            out.flush();
            out.close();
            // 定义BufferedReader输入流来读取URL的响应
            int code = conn.getResponseCode();
            System.out.print("====="+conn.getResponseMessage());
            if (HttpURLConnection.HTTP_OK == code) {
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    sub.append(line);
                }
                in.close();
            }
            return sub.toString();
        } catch (IOException e) {
            sub = new StringBuilder();
            System.out.println("调用kettle服务失败:"+";urlPath="+urlPath+";data:"+urlPath+"Message:"+e.getMessage());
        }
        return sub.toString();
    }
    public static int getSecondTimestamp(Date date){
        if (null == date) {
            return 0;
        }
        String timestamp = String.valueOf(date.getTime());
        int length = timestamp.length();
        if (length > 3) {
            return Integer.valueOf(timestamp.substring(0,length-3));
        } else {
            return 0;
        }
    }

    private static String HMAC_ALGORITHM = "HmacSHA256";

    private static char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    static String bytesToHex(byte[] bytes) {

        char[] buf = new char[bytes.length * 2];
        int index = 0;
        for (byte b : bytes) {
            buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
            buf[index++] = HEX_CHAR[b & 0xf];
        }

        return new String(buf);
    }

    /**
     * 生成签名,开发版本oracle jdk 1.8.0_221
     *
     * @param secretId        邮件下发的secret_id
     * @param secretKey       邮件下发的secret_key
     * @param httpMethod      http请求方法 GET/POST/PUT等
     * @param headerNonce     X-TC-Nonce请求头,随机数
     * @param headerTimestamp X-TC-Timestamp请求头,当前时间的秒级时间戳
     * @param requestUri      请求uri,eg:/v1/meetings
     * @param requestBody     请求体,没有的设为空串
     * @return 签名,需要设置在请求头X-TC-Signature中
     * @throws NoSuchAlgorithmException e
     * @throws InvalidKeyException      e
     */
    static String sign(String secretId, String secretKey, String httpMethod, String headerNonce, String headerTimestamp, String requestUri, String requestBody)
            throws NoSuchAlgorithmException, InvalidKeyException {

        String tobeSig =
                httpMethod + "\nX-TC-Key=" + secretId + "&X-TC-Nonce=" + headerNonce + "&X-TC-Timestamp=" + headerTimestamp + "\n" + requestUri + "\n" + requestBody;
        Mac mac = Mac.getInstance(HMAC_ALGORITHM);
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), mac.getAlgorithm());
        mac.init(secretKeySpec);
        byte[] hash = mac.doFinal(tobeSig.getBytes(StandardCharsets.UTF_8));
        String hexHash = bytesToHex(hash);
        return new String(Base64.getEncoder().encode(hexHash.getBytes(StandardCharsets.UTF_8)));
    }
}
发布了7 篇原创文章 · 获赞 1 · 访问量 6153

猜你喜欢

转载自blog.csdn.net/sherazade/article/details/105411069
今日推荐