All Products
Search
Document Center

:Sample code

Last Updated:Apr 07, 2024

To call API operations of ApsaraVideo Media Processing (MPS), you can send a request to the MPS server over HTTP or HTTPS. Then, the MPS server returns a response. After the MPS server receives a request, it performs authentication and parameter verification on the request. After the authentication and parameter verification are passed, the MPS server submits or completes the required operation based on the parameters specified in the request and returns the processing results in an HTTP response to the caller.

Procedure

  1. Prepare request parameters.

  2. Create a canonicalized query string by using request parameters.

  3. Create a string-to-sign.

  4. Calculate the HMAC value of the string-to-sign and encode the HMAC value in Base64.

  5. Create a request URL.

The following sample code provides an example on how to construct a request in Java:

Set global parameters


private static final String ENCODE_TYPE = "UTF-8";
private static final String ALGORITHM = "HmacSHA1";
private static final String HTTP_METHOD = "GET";
private static final String SEPARATOR = "&";
private static final String EQUAL = "=";

Prepare request parameters


Map parameterMap = new HashMap();
// Common request parameters.
parameterMap.put("Action", "SearchTemplate");
parameterMap.put("Version", "2014-06-18");
parameterMap.put("AccessKeyId", "testId"); // Replace testId with your own AccessKey ID.
parameterMap.put("Timestamp", "2015-05-14T09:03:45Z");// This timestamp is fixed for test. In this way, the signature value generated in the sample code remains unchanged, and you can easily compare and verify the data. To generate a variable timestamp, replace this line of code with the following one:
//parameterMap.put("Timestamp", formatIso8601Date(new Date())); 
parameterMap.put("SignatureMethod", "HMAC-SHA1");
parameterMap.put("SignatureVersion", "1.0");
parameterMap.put("SignatureNonce", "4902260a-516a-4b6a-a455-45b653cf6150"); // The unique random number is fixed for test. In this way, the signature value generated in the sample code remains unchanged, and you can easily compare and verify the data. To generate a variable unique random number, replace this line of code with the following one:
//parameterMap.put("SignatureNonce", UUID.randomUUID().toString());
parameterMap.put("Format", "XML"); // The JSON format is also supported.

Use the request parameters to construct a canonicalized query string


private static String percentEncode(String value) throws UnsupportedEncodingException {
return URLEncoder.encode(value, ENCODE_TYPE).replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
}
private static String buildCanonicalizedQueryString(Map parameterMap) throws UnsupportedEncodingException {
// Sort the parameters.
List sortedKeys = new ArrayList(parameterMap.keySet());
Collections.sort(sortedKeys);
StringBuilder temp = new StringBuilder();
for (String key : sortedKeys) {
// Encode the parameters and values.
String value = parameterMap.get(key);
temp.append(SEPARATOR).append(percentEncode(key)).append(EQUAL).append(percentEncode(value));
}
return temp.toString().substring(1);
}

Calculate the HMAC value of the string-to-sign and encode the HMAC value in Base64


private static String buildStringToSign(String canonicalizedQueryString) throws UnsupportedEncodingException {
// Generate the string-to-sign.
StringBuilder temp = new StringBuilder();
temp.append(HTTP_METHOD).append(SEPARATOR);
temp.append(percentEncode("/")).append(SEPARATOR);
// Encode the canonicalized query string.
temp.append(percentEncode(canonicalizedQueryString));
return temp.toString();
}
private static String buildSignature(String keySecret, String stringToSign) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
SecretKey key = new SecretKeySpec((keySecret + SEPARATOR).getBytes(ENCODE_TYPE), SignatureMethod.HMAC_SHA1);
Mac mac = Mac.getInstance(ALGORITHM);
mac.init(key);
byte[] hashBytes = mac.doFinal(stringToSign.toString().getBytes(ENCODE_TYPE));
byte[] base64Bytes = new Base64().encode(hashBytes);
String base64UTF8String = new String(base64Bytes, "utf-8");
return URLEncoder.encode(base64UTF8String, ENCODE_TYPE);
}

Create a request URL


private static String buildRequestURL(String signature, Map parameterMap) throws UnsupportedEncodingException {
// Generate a request URL.
StringBuilder temp = new StringBuilder("http://mts.aliyuncs.com/?");
temp.append(URLEncoder.encode("Signature", ENCODE_TYPE)).append("=").append(signature);
for (Map.Entry e : parameterMap.entrySet()) {
temp.append("&").append(percentEncode(e.getKey())).append("=").append(percentEncode(e.getValue()));
}
return temp.toString();
}

Example

  • Prepare request parameters.

    • Set the AccessKeyId parameter to testId.

    • Set the AccessKey secret to testKeySecret.

    • Set the Timestamp parameter to 2015-05-14T09:03:45Z.

    • Set the SignatureNonce parameter to 4902260a-516a-4b6a-a455-45b653cf6150.

    • Set the Action parameter to SearchTemplate and the PageSize parameter to 2.

    • Set the Format parameter to XML.

  • Use the request parameters to construct a canonicalized query string.

    AccessKeyId=testId&Action=SearchTemplate&Format=XML&PageSize=2&SignatureMethod=HMAC-SHA1&SignatureNonce=4902260a-516a-4b6a-a455-45b653cf6150&SignatureVersion=1.0&Timestamp=2015-05-14T09%3A03%3A45Z&Version=2014-06-18
  • Create a string-to-sign.

    GET&%2F&AccessKeyId%3DtestId&Action%3DSearchTemplate&Format%3DXML&PageSize%3D2&SignatureMethod%3DHMAC-SHA1&SignatureNonce%3D4902260a-516a-4b6a-a455-45b653cf6150&SignatureVersion%3D1.0&Timestamp%3D2015-05-14T09%253A03%253A45Z&Version%3D2014-06-18
  • Calculate the HMAC value of the string-to-sign and encode the HMAC value in Base64.

    kmDv4mWo806GWPjQMy2z4VhBBDQ%3D
  • Create a request URL.

    http://mts.cn-hangzhou.aliyuncs.com/?Signature=kmDv4mWo806GWPjQMy2z4VhBBDQ%3D&SignatureVersion=1.0&Action=SearchTemplate&Format=XML&SignatureNonce=4902260a-516a-4b6a-a455-45b653cf6150&PageSize=2&Version=2014-06-18&AccessKeyId=testId&SignatureMethod=HMAC-SHA1&Timestamp=2015-05-14T09%3A03%3A45Z
  • Send an HTTP request to the URL and obtain a response from the server. For example, you can send the request by using cURL. The response in this example is returned in XML format.

    <SearchTemplateResponse>
            <RequestId>017F1B2D-2B5B-4441-ABBA-E0DC08F5AFEC</RequestId>
            <Template>
                <Id>88c6ca184c0e47098a5b665e2a126799</Id>
                <Name>MTS-example</Name>
                <Container>
                    <Format>mp4</Format>
                </Container>
                <Video>
                    <Codec>H.264</Codec>
                    <Profile>high</Profile>
                    <Bitrate>Auto</Bitrate>
                    <Crf>15</Crf>
                    <Width>256</Width>
                    <Height>800</Height>
                    <Fps>25</Fps>
                    <Gop>10</Gop>
                    <Preset>lower</Preset>
                    <ScanMode></ScanMode>
                    <Bufsize>6000</Bufsize>
                    <Maxrate></Maxrate>
                    <BitrateBnd>
                       <Max></Max>
                       <Min></Min>
                    </BitrateBnd>
                </Video>
                <Audio>
                    <Codec>aac</Codec>
                    <Samplerate>44100</Samplerate>
                    <Bitrate>500</Bitrate>
                    <Channels>2</Channels>
                </Audio>
                <State>Normal</State>
            </Template>
        </SearchTemplateResponse>