全部产品
弹性计算 会员服务 网络 安全 移动云 数加·大数据分析及展现 数加·大数据应用 管理与监控 云通信 阿里云办公 培训与认证 更多
存储与CDN 数据库 域名与网站(万网) 应用服务 数加·人工智能 数加·大数据基础服务 互联网中间件 视频服务 开发者工具 解决方案 物联网 智能硬件
视频点播

调用示例

更新时间:2018-04-23 14:51:07

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

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

  • 添加Jar包依赖

    注:使用httpclient get请求

    1. <dependency>
    2. <groupId>org.apache.httpcomponents</groupId>
    3. <artifactId>httpclient</artifactId>
    4. <version>4.5.1</version>
    5. </dependency>
  • JAVA代码

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

最后得到的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. }
本文导读目录