最近疫情嚴重,公司準備出一個在線視頻會議功能,需要調用騰訊會議的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="這裏請輸入你們公司的SecretId";
String SecretKey="這裏請輸入你們公司的SecretKey";
String appId="這裏請輸入你們公司的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)));
}
}