視頻點播的調用示例有哪些?

阿裏雲問答 2022-01-07 05:18:40 阅读数:829

示例

視頻點播的調用示例有哪些?




采納答案1:

調用視頻點播服務接口,是向視頻點播服務端發送HTTP請求(可通過HTTP或HTTPS通道發送),並獲取響應結果的過程。視頻點播服務端接收到用戶請求後,對請求進行身份驗證和參數驗證,驗證成功後,根據請求的指定參數提交或完成相應操作,並把處理結果以HTTP響應的形式返回給調用者。

以下Java示例代碼演示了如何添加公共參數和私有參數、如何用請求參數構造規範化請求字符串、如何構造StringToSign字符串,以及如何獲得OpenAPI地址,最終以Get方式發送Http請求,獲取相應的響應結果。如果您需要使用以下示例,請替換示例中的必選參數及私有參數。

添加jar包依賴 注意:使用httpclient get請求 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.1</version> </dependency>JAVA代碼import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import sun.misc.BASE64Encoder;import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.URI;import java.net.URISyntaxException;import java.net.URLEncoder;import java.security.SignatureException;import java.text.SimpleDateFormat;import java.util.*;import java.util.logging.Logger;/** * 視頻點播OpenAPI調用示例 * 以GetVideoPlayAuth接口為例,其他接口請替換相應接口名稱及私有參數 */public class Main { //賬號AccessKey信息請填寫(必選) private static String access_key_id = ""; //賬號AccessKey信息請填寫(必選) private static String access_key_secret = ""; //STS臨時授權方式訪問時該參數為必選,使用主賬號AccessKey和RAM子賬號AccessKey不需要填寫 private static String security_token = ""; //以下參數不需要修改 private final static String VOD_DOMAIN = "http://vod.cn-shanghai.aliyuncs.com"; private final static String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; private final static String HTTP_METHOD = "GET"; private final static String HMAC_SHA1_ALGORITHM = "HmacSHA1"; private final static String UTF_8 = "utf-8"; private final static Logger LOG = Logger.getLogger(Main.class.getName());public static void main(String[] args) throws Exception { //生成私有參數,不同API需要修改 Map<String, String> privateParams = generatePrivateParamters(); //生成公共參數,不需要修改 Map<String, String> publicParams = generatePublicParamters(); //生成OpenAPI地址,不需要修改 String URL = generateOpenAPIURL(publicParams, privateParams); //發送HTTP GET 請求 httpGet(URL);} /** * 生成視頻點播OpenAPI私有參數 * 不同API需要修改此方法中的參數 * @return */private static Map<String, String> generatePrivateParamters() { // 接口私有參數列錶, 不同API請替換相應參數 Map<String, String> privateParams = new HashMap<>(); // 視頻ID privateParams.put("VideoId","5aed81b74ba84920be578cdfe004af4b"); // API名稱 privateParams.put("Action", "GetVideoPlayAuth"); return privateParams;} /** * 生成視頻點播OpenAPI公共參數 * 不需要修改 * @return */private static Map<String, String> generatePublicParamters() { Map<String, String> publicParams = new HashMap<>(); publicParams.put("Format", "JSON"); publicParams.put("Version", "2017-03-21"); publicParams.put("AccessKeyId", access_key_id); publicParams.put("SignatureMethod", "HMAC-SHA1"); publicParams.put("Timestamp", generateTimestamp()); publicParams.put("SignatureVersion", "1.0"); publicParams.put("SignatureNonce", generateRandom()); if (security_token != null && security_token.length() > 0) { publicParams.put("SecurityToken", security_token); } return publicParams;} /** * 生成OpenAPI地址 * @param privateParams * @return * @throws Exception */private static String generateOpenAPIURL(Map<String, String> publicParams, Map<String, String> privateParams) { return generateURL(VOD_DOMAIN, HTTP_METHOD, publicParams, privateParams);}/** * @param domain 請求地址 * @param httpMethod HTTP請求方式GET,POST等 * @param publicParams 公共參數 * @param privateParams 接口的私有參數 * @return 最後的url */private static String generateURL(String domain, String httpMethod, Map<String, String> publicParams, Map<String, String> privateParams) { List<String> allEncodeParams = getAllParams(publicParams, privateParams); String cqsString = getCQS(allEncodeParams); out("CanonicalizedQueryString = " + cqsString); String stringToSign = httpMethod + "&" + percentEncode("/") + "&" + percentEncode(cqsString); out("StringtoSign = " + stringToSign); String signature = hmacSHA1Signature(access_key_secret, stringToSign); out("Signature = " + signature); return domain + "?" + cqsString + "&" + percentEncode("Signature") + "=" + percentEncode(signature);}private static List<String> getAllParams(Map<String, String> publicParams, Map<String, String> privateParams) { List<String> encodeParams = new ArrayList<String>(); if (publicParams != null) { for (String key : publicParams.keySet()) { String value = publicParams.get(key); //將參數和值都urlEncode一下。 String encodeKey = percentEncode(key); String encodeVal = percentEncode(value); encodeParams.add(encodeKey + "=" + encodeVal); } } if (privateParams != null) { for (String key : privateParams.keySet()) { String value = privateParams.get(key); //將參數和值都urlEncode一下。 String encodeKey = percentEncode(key); String encodeVal = percentEncode(value); encodeParams.add(encodeKey + "=" + encodeVal); } } return encodeParams;}/*** 參數urlEncode** @param value* @return*/private static String percentEncode(String value) { try { String urlEncodeOrignStr = URLEncoder.encode(value, "UTF-8"); String plusReplaced = urlEncodeOrignStr.replace("+", "%20"); String starReplaced = plusReplaced.replace("*", "%2A"); String waveReplaced = starReplaced.replace("%7E", "~"); return waveReplaced; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return value;}/*** 獲取CQS 的字符串** @param allParams* @return*/private static String getCQS(List<String> allParams) { ParamsComparator paramsComparator = new ParamsComparator(); Collections.sort(allParams, paramsComparator); String cqString = ""; for (int i = 0; i < allParams.size(); i++) { cqString += allParams.get(i); if (i != allParams.size() - 1) { cqString += "&"; } } return cqString;}private static class ParamsComparator implements Comparator<String> { @Override public int compare(String lhs, String rhs) { return lhs.compareTo(rhs); }}private static String hmacSHA1Signature(String accessKeySecret, String stringtoSign) { try { String key = accessKeySecret + "&"; try { SecretKeySpec signKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signKey); byte[] rawHmac = mac.doFinal(stringtoSign.getBytes()); //按照Base64 編碼規則把上面的 HMAC 值編碼成字符串,即得到簽名值(Signature) return new String(new BASE64Encoder().encode(rawHmac)); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } } catch (SignatureException e) { e.printStackTrace(); } return "";}/*** 生成隨機數** @return*/private static String generateRandom() { String signatureNonce = UUID.randomUUID().toString(); return signatureNonce;}/*** 生成當前UTC時間戳** @return*/public static String generateTimestamp() { Date date = new Date(System.currentTimeMillis()); SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT); df.setTimeZone(new SimpleTimeZone(0, "GMT")); return df.format(date);}private static String httpGet(String url) throws Exception { CloseableHttpClient httpClient = null; try { httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(); httpGet.setURI(new URI(url)); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(3000) .setSocketTimeout(3000) .build(); httpGet.setConfig(requestConfig); HttpResponse result = httpClient.execute(httpGet); String str; try { /**讀取服務器返回過來的json字符串數據**/ str = EntityUtils.toString(result.getEntity()); EntityUtils.consume(result.getEntity()); } catch (Exception e) { e.printStackTrace(); throw e; } out(str); // 這裏可以解析視頻雲點播服務端的響應結果 return str; } catch (URISyntaxException e) { e.printStackTrace(); throw e; } catch (ClientProtocolException e) { e.printStackTrace(); throw e; } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { if (httpClient != null) httpClient.close(); } catch (Exception e) { e.printStackTrace(); throw e; } }}private static void out(String newLine) { System.out.println(newLine); LOG.info(newLine);}}

最終得到URL:

http://vod.cn-shanghai.aliyuncs.com?Signature=UI%2FwKfuvTtphzCKHwPhP0ErtLnc%3D&SignatureVersion=1.0&Action=GetVideoPlayAuth&Format=JSON&VideoId=68a4d2629a339db3207963ac073a88cd&SignatureNonce=578a50c1-280d-4a34-bffc-e06aa6b2df76&Version=2017-03-21&AccessKeyId=testId&SignatureMethod=HMAC-SHA1&Timestamp=2017-03-29T12%3A09%3A11Z

通過HTTP請求的方式向上述URL地址發送HTTP請求,得到響應結果,此處以JSON格式為例:

{ "RequestId": "25818875-5F78-4A13-BEF6-D7393642CA58", "VideoMeta": { "VideoId": "93ab850b4f6f44eab54b6e91d24d81d4", "Title": "阿裏雲VOD", "Duration": 135.6, "CoverURL": "https://image.example.com/sample.jpg", "Status": "Normal" }, "PlayAuth": "sstyYuew678999ew90000000xtt7TYUh"}

版权声明:本文为[阿裏雲問答]所创,转载请带上原文链接,感谢。 https://gsmany.com/2022/01/202201070518400807.html