全部产品
存储与CDN 数据库 安全 应用服务 数加·人工智能 数加·大数据基础服务 互联网中间件 视频服务 开发者工具 解决方案 物联网
视频点播

调用示例

更新时间:2017-10-16 14:28:19

调用示例

对视频点播服务接口的调用是通过向视频点播服务端发送HTTP请求(可以通过HTTP或HTTPS通道发送),并获取视频点播服务对该请求响应结果的过程。视频点播服务端在接收到用户请求后,对请求做必要的身份验证和参数验证,在所有验证成功后根据请求的指定参数提交或完成相应操作,并把处理的结果以HTTP响应的形式返回给调用者。

以下Java示例代码演示了如何添加公共参数和私有参数、如何构造用请求参数构造规范化请求字符串,如何构造stringToSign字符串,以及如何得到OpenAPI地址,最终以Get方式发送Http请求后得到相应响应。如果您需要使用以下示例,请替换示例中的必选参数及私有参数。

  1. import sun.misc.BASE64Encoder;
  2. import javax.crypto.Mac;
  3. import javax.crypto.spec.SecretKeySpec;
  4. import java.io.IOException;
  5. import java.io.UnsupportedEncodingException;
  6. import java.net.URL;
  7. import java.net.URLEncoder;
  8. import java.security.SignatureException;
  9. import java.text.SimpleDateFormat;
  10. import java.util.*;
  11. import java.util.logging.Level;
  12. import java.util.logging.Logger;
  13. /**
  14. * 视频点播OpenAPI调用示例
  15. * 以GetVideoPlayAuth接口为例,其他接口请替换相应接口名称及私有参数
  16. */
  17. public class Main {
  18. //账号AK信息请填写(必选)
  19. private static String access_key_id = "";
  20. //账号AK信息请填写(必选)
  21. private static String access_key_secret = "";
  22. //STS临时授权方式访问时该参数为必选,使用主账号AK和RAM子账号AK不需要填写
  23. private static String security_token = "";
  24. //以下参数不需要修改
  25. private final static String VOD_DOMAIN = "http://vod.cn-shanghai.aliyuncs.com";
  26. private final static String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
  27. private final static String HTTP_METHOD = "GET";
  28. private final static String HMAC_SHA1_ALGORITHM = "HmacSHA1";
  29. private final static String UTF_8 = "utf-8";
  30. private final static Logger LOG = Logger.getLogger(Main.class.getName());
  31. public static void main(String[] args) throws IOException {
  32. //生成私有参数,不同API需要修改
  33. Map<String, String> privateParams = generatePrivateParamters();
  34. //生成公共参数,不需要修改
  35. Map<String, String> publicParams = generatePublicParamters();
  36. //生成OpenAPI地址,不需要修改
  37. String URL = generateOpenAPIURL(publicParams, privateParams);
  38. //发送HTTP GET 请求
  39. httpGet(URL);
  40. }
  41. /**
  42. * 生成视频点播OpenAPI私有参数
  43. * 不同API需要修改此方法中的参数
  44. * @return
  45. */
  46. private static Map<String, String> generatePrivateParamters() {
  47. // 接口私有参数列表, 不同API请替换相应参数
  48. Map<String, String> privateParams = new HashMap<>();
  49. // 视频ID
  50. privateParams.put("VideoId","5aed81b74ba84920be578cdfe004af4b");
  51. // API名称
  52. privateParams.put("Action", "GetVideoPlayAuth");
  53. return privateParams;
  54. }
  55. /**
  56. * 生成视频点播OpenAPI公共参数
  57. * 不需要修改
  58. * @return
  59. */
  60. private static Map<String, String> generatePublicParamters() {
  61. Map<String, String> publicParams = new HashMap<>();
  62. publicParams.put("Format", "JSON");
  63. publicParams.put("Version", "2017-03-21");
  64. publicParams.put("AccessKeyId", access_key_id);
  65. publicParams.put("SignatureMethod", "HMAC-SHA1");
  66. publicParams.put("Timestamp", generateTimestamp());
  67. publicParams.put("SignatureVersion", "1.0");
  68. publicParams.put("SignatureNonce", generateRandom());
  69. if (security_token != null && security_token.length() > 0) {
  70. publicParams.put("SecurityToken", security_token);
  71. }
  72. return publicParams;
  73. }
  74. /**
  75. * 生成OpenAPI地址
  76. * @param privateParams
  77. * @return
  78. * @throws Exception
  79. */
  80. private static String generateOpenAPIURL(Map<String, String> publicParams, Map<String, String> privateParams) {
  81. return generateURL(VOD_DOMAIN, HTTP_METHOD, publicParams, privateParams);
  82. }
  83. /**
  84. * @param domain 请求地址
  85. * @param httpMethod HTTP请求方式GET,POST等
  86. * @param publicParams 公共参数
  87. * @param privateParams 接口的私有参数
  88. * @return 最后的url
  89. */
  90. private static String generateURL(String domain, String httpMethod, Map<String, String> publicParams, Map<String, String> privateParams) {
  91. List<String> allEncodeParams = getAllParams(publicParams, privateParams);
  92. String cqsString = getCQS(allEncodeParams);
  93. out("CanonicalizedQueryString = " + cqsString);
  94. String stringToSign = httpMethod + "&" + percentEncode("/") + "&" + percentEncode(cqsString);
  95. out("StringtoSign = " + stringToSign);
  96. String signature = hmacSHA1Signature(access_key_secret, stringToSign);
  97. out("Signature = " + signature);
  98. return domain + "?" + cqsString + "&" + percentEncode("Signature") + "=" + percentEncode(signature);
  99. }
  100. private static List<String> getAllParams(Map<String, String> publicParams, Map<String, String> privateParams) {
  101. List<String> encodeParams = new ArrayList<String>();
  102. if (publicParams != null) {
  103. for (String key : publicParams.keySet()) {
  104. String value = publicParams.get(key);
  105. //将参数和值都urlEncode一下。
  106. String encodeKey = percentEncode(key);
  107. String encodeVal = percentEncode(value);
  108. encodeParams.add(encodeKey + "=" + encodeVal);
  109. }
  110. }
  111. if (privateParams != null) {
  112. for (String key : privateParams.keySet()) {
  113. String value = privateParams.get(key);
  114. //将参数和值都urlEncode一下。
  115. String encodeKey = percentEncode(key);
  116. String encodeVal = percentEncode(value);
  117. encodeParams.add(encodeKey + "=" + encodeVal);
  118. }
  119. }
  120. return encodeParams;
  121. }
  122. /**
  123. * 参数urlEncode
  124. *
  125. * @param value
  126. * @return
  127. */
  128. private static String percentEncode(String value) {
  129. try {
  130. String urlEncodeOrignStr = URLEncoder.encode(value, "UTF-8");
  131. String plusReplaced = urlEncodeOrignStr.replace("+", "%20");
  132. String starReplaced = plusReplaced.replace("*", "%2A");
  133. String waveReplaced = starReplaced.replace("%7E", "~");
  134. return waveReplaced;
  135. } catch (UnsupportedEncodingException e) {
  136. e.printStackTrace();
  137. }
  138. return value;
  139. }
  140. /**
  141. * 获取CQS 的字符串
  142. *
  143. * @param allParams
  144. * @return
  145. */
  146. private static String getCQS(List<String> allParams) {
  147. ParamsComparator paramsComparator = new ParamsComparator();
  148. Collections.sort(allParams, paramsComparator);
  149. String cqString = "";
  150. for (int i = 0; i < allParams.size(); i++) {
  151. cqString += allParams.get(i);
  152. if (i != allParams.size() - 1) {
  153. cqString += "&";
  154. }
  155. }
  156. return cqString;
  157. }
  158. private static class ParamsComparator implements Comparator<String> {
  159. @Override
  160. public int compare(String lhs, String rhs) {
  161. return lhs.compareTo(rhs);
  162. }
  163. }
  164. private static String hmacSHA1Signature(String accessKeySecret, String stringtoSign) {
  165. try {
  166. String key = accessKeySecret + "&";
  167. try {
  168. SecretKeySpec signKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
  169. Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
  170. mac.init(signKey);
  171. byte[] rawHmac = mac.doFinal(stringtoSign.getBytes());
  172. //按照Base64 编码规则把上面的 HMAC 值编码成字符串,即得到签名值(Signature)
  173. return new String(new BASE64Encoder().encode(rawHmac));
  174. } catch (Exception e) {
  175. throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
  176. }
  177. } catch (SignatureException e) {
  178. e.printStackTrace();
  179. }
  180. return "";
  181. }
  182. /**
  183. * 生成随机数
  184. *
  185. * @return
  186. */
  187. private static String generateRandom() {
  188. String signatureNonce = UUID.randomUUID().toString();
  189. return signatureNonce;
  190. }
  191. /**
  192. * 生成当前UTC时间戳
  193. *
  194. * @return
  195. */
  196. public static String generateTimestamp() {
  197. Date date = new Date(System.currentTimeMillis());
  198. SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT);
  199. df.setTimeZone(new SimpleTimeZone(0, "GMT"));
  200. return df.format(date);
  201. }
  202. private static String httpGet(String url) throws IOException {
  203. /*
  204. * Read and covert a inputStream to a String.
  205. * Referred this:
  206. * http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
  207. */
  208. out("URL = " + url);
  209. @SuppressWarnings("resource")
  210. Scanner s = new Scanner(new URL(url).openStream(), UTF_8).useDelimiter("\\A");
  211. try {
  212. String resposne = s.hasNext() ? s.next() : "true";
  213. out("Response = " + resposne);
  214. return resposne;
  215. } finally {
  216. s.close();
  217. }
  218. }
  219. private static void out(String newLine) {
  220. LOG.log(Level.INFO, newLine);
  221. }
  222. }

最后得到的URL为:

  1. 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:

  1. {
  2. "RequestId": "25818875-5F78-4A13-BEF6-D7393642CA58",
  3. "VideoMeta": {
  4. "VideoId": "93ab850b4f6f44eab54b6e91d24d81d4",
  5. "Title": "阿里云VOD",
  6. "Duration": 135.6,
  7. "CoverURL": "https://image.example.com/sample.jpg",
  8. "Status": "Normal"
  9. },
  10. "PlayAuth": "sstyYuew678999ew90000000xtt7TYUh"
  11. }
本文导读目录