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.
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
Java code
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;
/**
* ApsaraVideo for VOD open API call example
* The following example calls the GetVideoPlayAuth operation. To call other operations, replace the corresponding operation name and private parameters.
*/
public class Main {
// Enter your AccessKey information. This parameter is required.
private static String access_key_id = "";
// Enter your AccessKey information. This parameter is required.
private static String access_key_secret = "";
// 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.
private static String security_token = "";
// Do not modify the following parameters.
private final static String VOD_DOMAIN = "http://vod.cn-shanghai.aliyuncs.com";
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 private parameters and modify 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 open 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 ApsaraVideo for VOD open API private parameters.
* Modify the parameters in the code based on the operation to be called.
* @return
*/
private static Map<String, String> generatePrivateParamters() {
// The list of private parameters. Replace parameters in the code based on the operation to be called.
Map<String, String> privateParams = new HashMap<>();
// The video ID.
privateParams.put("VideoId","5aed81b74ba84920be578cdfe004af4b");
// The operation that you want to perform.
privateParams.put("Action", "GetVideoPlayAuth");
return privateParams;
}
/**
* Generate ApsaraVideo for VOD open API common parameters.
* 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 open 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 address.
* @param httpMethod // The HTTP request method, such as GET or POST.
* @param publicParams // The common parameters.
* @param privateParams // The private parameters.
* @return // The final 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 CQS 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());
// According to the Base64 encoding rules, encode the preceding HMAC value to obtain the signature string (the value of the Signature parameter).
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 representing 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-formatted string 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 for 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);
}
}
Obtain the final 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 example shows a response in JSON format.
{
"RequestId": "25818875-5F78-4A13-BEF6-D7393642CA58",
"VideoMeta": {
"VideoId": "93ab850b4f6f44eab54b6e91d24d81d4",
"Title": "ApsaraVideo for VOD",
"Duration": 135.6,
"CoverURL": "https://image.example.com/sample.jpg",
"Status": "Normal"
},
"PlayAuth": "sstyYuew678999ew90000000xtt7TYUh"
}