All Products
Search
Document Center

Call Examples

Last Updated: Mar 04, 2019

When you call an ApsaraVideo for VOD operation, you send an HTTP request to the ApsaraVideo for VOD server over HTTP or HTTPS to obtain a response. After receiving the request, the ApsaraVideo for VOD server verifies the user identity and request parameters. After the verification succeeds, the server submits or completes the relevant operation based on the specified parameters in the request, and returns the processing result to you in an HTTP response.

The following Java sample code demonstrates how to add common and private parameters, use request parameters to construct a canonicalized query string, construct a StringToSign string, obtain an open API request URL, and finally use the GET method to send an HTTP request to obtain the corresponding response. To use the following examples, you need to replace the required and private parameters in the examples.

  • Add JAR package dependencies

    Note: Use the HttpClient GET request method.

    1. <dependency>
    2. <groupId>org.apache.httpcomponents</groupId>
    3. <artifactId>httpclient</artifactId>
    4. <version>4.5.1</version>
    5. </dependency>
  • Java code

  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. * ApsaraVideo for VOD open API call example
  22. * The following example calls the GetVideoPlayAuth operation. To call other operations, replace the corresponding operation name and private parameters.
  23. */
  24. public class Main {
  25. // Enter your AccessKey information. This parameter is required.
  26. private static String access_key_id = "";
  27. // Enter your AccessKey information. This parameter is required.
  28. private static String access_key_secret = "";
  29. // Specify the token for STS authorization. This parameter is required for STS authorization and not required when the AccessKey of your Alibaba Cloud account or RAM user is used.
  30. private static String security_token = "";
  31. // Do not modify the following parameters.
  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. // Generate private parameters and modify the parameters in the code based on the operation to be called.
  40. Map<String, String> privateParams = generatePrivateParamters();
  41. // Generate common parameters and do not modify the parameters in the code.
  42. Map<String, String> publicParams = generatePublicParamters();
  43. // Generate an open API request URL and do not modify the parameters in the code.
  44. String URL = generateOpenAPIURL(publicParams, privateParams);
  45. // Send an HTTP GET request.
  46. httpGet(URL);
  47. }
  48. /**
  49. * Generate ApsaraVideo for VOD open API private parameters.
  50. * Modify the parameters in the code based on the operation to be called.
  51. * @return
  52. */
  53. private static Map<String, String> generatePrivateParamters() {
  54. // The list of private parameters. Replace parameters in the code based on the operation to be called.
  55. Map<String, String> privateParams = new HashMap<>();
  56. // The video ID.
  57. privateParams.put("VideoId","5aed81b74ba84920be578cdfe004af4b");
  58. // The operation that you want to perform.
  59. privateParams.put("Action", "GetVideoPlayAuth");
  60. return privateParams;
  61. }
  62. /**
  63. * Generate ApsaraVideo for VOD open API common parameters.
  64. * Do not modify the parameters in the code.
  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. * Generate an open API request URL.
  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 // The request address.
  92. * @param httpMethod // The HTTP request method, such as GET or POST.
  93. * @param publicParams // The common parameters.
  94. * @param privateParams // The private parameters.
  95. * @return // The final 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. // Perform URL encoding for the parameter names and values.
  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. // Perform URL encoding for the parameter names and values.
  122. String encodeKey = percentEncode(key);
  123. String encodeVal = percentEncode(value);
  124. encodeParams.add(encodeKey + "=" + encodeVal);
  125. }
  126. }
  127. return encodeParams;
  128. }
  129. /**
  130. * Perform URL encoding for the parameters.
  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. * Obtain a CQS string.
  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. // According to the Base64 encoding rules, encode the preceding HMAC value to obtain the signature string (the value of the Signature parameter).
  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. * Generate a random number.
  191. *
  192. * @return
  193. */
  194. private static String generateRandom() {
  195. String signatureNonce = UUID.randomUUID().toString();
  196. return signatureNonce;
  197. }
  198. /**
  199. * Generate a timestamp representing the current UTC time.
  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. /**Read the JSON-formatted string returned from the server.**/
  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. // Parse the response from the ApsaraVideo for VOD server.
  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. }

Obtain the final 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

Send an HTTP request to the preceding URL. Then, you can receive a response. The following example shows a response in JSON format.

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