All Products
Search
Document Center

Call examples

Last Updated: Nov 01, 2021

When you call an API operation of ApsaraVideo VOD, you send an HTTP request to the ApsaraVideo VOD server over HTTP or HTTPS to obtain a response. After the ApsaraVideo VOD server receives a user request, the server performs authentication and parameter verification on the request. After the authentication and verification succeed, the server submits or completes the required operation based on the parameters that are specified in the request. The server then returns the processing results in an HTTP response to the caller.

The following sample code in Java provides examples on how to add common and operation-specific parameters, use request parameters to construct a canonicalized query string, construct a string-to-sign, obtain an API request URL, and then use the GET method to send an HTTP request to obtain the corresponding response. To use the following sample code, you must replace the required and operation-specific parameters in the examples.

  • Add a JAR package dependency

    Notice

    Use the HttpClient GET request method.

      <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.1</version>
      </dependency>
                                    
  • Sample code in 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;
    /**
     * API call example of ApsaraVideo VOD
     * In the following example, the GetVideoPlayAuth operation is called. To call other operations, replace the operation name and operation-specific parameters.
     */
    public class Main {
            // Enter your AccessKey ID. This parameter is required.
            private static String access_key_id = "";
            // Enter your AccessKey secret. This parameter is required.
            private static String access_key_secret = "";
            // Specify the token for Security Token Service (STS) authorization. This parameter is required for STS authorization. If the AccessKey pair of your Alibaba Cloud account or a RAM user is used, this parameter is optional.
            private static String security_token = "";
            // The endpoint of the ApsaraVideo VOD API is vod.{ ApiRegion}.aliyuncs.com. Replace {ApiRegion} with the ID of the region where you want to call API operations.
            private final static String VOD_DOMAIN = "http://vod.cn-shanghai.aliyuncs.com";
            // Do not modify the following parameters:
            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 {
        // Generate operation-specific parameters and replace the parameters in the code based on the operation to be called.
        Map<String, String> privateParams = generatePrivateParamters();
        // Generate common parameters and do not modify the parameters in the code.
        Map<String, String> publicParams = generatePublicParamters();
        // Generate an API request URL and do not modify the parameters in the code.
        String URL = generateOpenAPIURL(publicParams, privateParams);
        // Send an HTTP GET request.
        httpGet(URL);
    }
      /**
        * Generate the operation-specific parameters of the ApsaraVideo VOD API.
        * Replace the parameters in the code based on the operation to be called.
        * @return
       */
    private static Map<String, String> generatePrivateParamters() {
        // The list of operation-specific parameters. Replace the parameters in the code based on the operation to be called.
        Map<String, String> privateParams = new HashMap<>();
        // The ID of the video.
        privateParams.put("VideoId","5aed81b74ba84920be578cdfe004af4b");
        // The operation that you want to perform.
        privateParams.put("Action", "GetVideoPlayAuth");
        return privateParams;
    }
      /**
       * Generate the common parameters of the ApsaraVideo VOD API.
       * Do not modify the parameters in the code.
       * @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;
    }
     /**
       * Generate an API request URL.
       * @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        The request URL.
      * @param httpMethod    The HTTP request method, such as GET or POST.
      * @param publicParams  The common parameters.
      * @param privateParams The operation-specific parameters.
      * @return The returned 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);
                // Perform URL encoding for the parameter names and values.
                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);
                // Perform URL encoding for the parameter names and values.
                String encodeKey = percentEncode(key);
                String encodeVal = percentEncode(value);
                encodeParams.add(encodeKey + "=" + encodeVal);
            }
        }
        return encodeParams;
    }
    /**
    * Perform URL encoding for the parameters.
    *
    * @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;
    }
    /**
    * Obtain a canonicalized query string.
    *
    * @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());
                            // Encode the preceding HMAC value in Base64 to obtain a signature string.
                            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 "";
    }
    /**
    * Generate a random number.
    *
    * @return
    */
    private static String generateRandom() {
            String signatureNonce = UUID.randomUUID().toString();
            return signatureNonce;
    }
    /**
    * Generate a timestamp that represents the current UTC time.
    *
    * @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 {
                /**Read the JSON string that is returned from the server.**/
                str = EntityUtils.toString(result.getEntity());
                EntityUtils.consume(result.getEntity());
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }
            out(str);
            // Parse the response from the ApsaraVideo VOD server.
            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);
    }
    }
                    

    Returned 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
                    

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

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