整体流程
使用视频点播实现音视频上传、存储、处理和播放的整体流程如下:
- 用户获取上传授权。
- VoD下发 上传地址和凭证 及 VideoId。
- 用户上传视频保存视频ID(VideoId)。
- 用户服务端根据VideoId获取播放凭证。
- VoD下发带时效的播放凭证。
- 用户服务端根据VideoId将播放凭证下发给客户端完成视频播放。
设置转码格式
选择全局设置 > 转码设置,单击添加转码模板组。
在视频转码模板组页面,根据业务需求选择封装格式和清晰度。
或直接将已有的模板设置为默认即可
配置域名
音视频上传完成后,必须配一个已备案的域名,并完成CNAME绑定
得到CNAME
在购买域名的服务商处的管理控制台配置域名解析
使用服务端API&SDK
简介
本文档介绍了点播服务的所有API列表,强烈推荐使用 服务端SDK 来调用API。使用API时,接入地址请参考 点播中心和访问域名,使用限制参考 点播使用限制。
-
- 获取账户的AccessKey ID / Key
2.3 设置不转码
测试之前现在 全局设置->转码设置 中设置“不转码”,以节省开发成本
- 服务端API
是需要我们自己写Http来请求访问;
参数:公共参数和私有参数
- 获取播放凭证,2、获取播放地址;都需要有共同的参数这种叫公共参数;
- 获取播放凭证独有的参数这种叫私有参数;
测试类:获取播放凭证!
package com.guli.vod;
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; /** * 视频点播OpenAPI调用示例 * 以GetVideoPlayAuth接口为例,其他接口请替换相应接口名称及私有参数 */ public class Main { //账号AccessKey信息请填写(必选) private static String access_key_id = "LTAIjDanEwf9RVXP"; //账号AccessKey信息请填写(必选) private static String access_key_secret = "v23qo8tptfAscACX44QO56XedG5Owk"; //STS临时授权方式访问时该参数为必选,使用主账号AccessKey和RAM子账号AccessKey不需要填写 private static String security_token = ""; //以下参数不需要修改 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 { //生成私有参数,不同API需要修改 Map<String, String> privateParams = generatePrivateParamters(); //生成公共参数,不需要修改 Map<String, String> publicParams = generatePublicParamters(); //生成OpenAPI地址,不需要修改 String URL = generateOpenAPIURL(publicParams, privateParams); //发送HTTP GET 请求 httpGet(URL); } /** * 生成视频点播OpenAPI私有参数 * 不同API需要修改此方法中的参数 * @return */ private static Map<String, String> generatePrivateParamters() { // 接口私有参数列表, 不同API请替换相应参数 Map<String, String> privateParams = new HashMap<>(); // 视频ID privateParams.put("VideoId","9b3bda52396641dbb14b71e2409eac1d"); // API名称 privateParams.put("Action", "GetVideoPlayAuth"); return privateParams; } /** * 生成视频点播OpenAPI公共参数 * 不需要修改 * @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; } /** * 生成OpenAPI地址 * @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 请求地址 * @param httpMethod HTTP请求方式GET,POST等 * @param publicParams 公共参数 * @param privateParams 接口的私有参数 * @return 最后的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); //将参数和值都urlEncode一下。 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); //将参数和值都urlEncode一下。 String encodeKey = percentEncode(key); String encodeVal = percentEncode(value); encodeParams.add(encodeKey + "=" + encodeVal); } } return encodeParams; } /** * 参数urlEncode * * @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; } /** * 获取CQS 的字符串 * * @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()); //按照Base64 编码规则把上面的 HMAC 值编码成字符串,即得到签名值(Signature) 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 ""; } /** * 生成随机数 * * @return */ private static String generateRandom() { String signatureNonce = UUID.randomUUID().toString(); return signatureNonce; } /** * 生成当前UTC时间戳 * * @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 { /**读取服务器返回过来的json字符串数据**/ str = EntityUtils.toString(result.getEntity()); EntityUtils.consume(result.getEntity()); } catch (Exception e) { e.printStackTrace(); throw e; } out(str); // 这里可以解析视频云点播服务端的响应结果 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); } } |
api请求原理
查看控制台的日志输出
(1)CanonicalizedQueryString:将所有私有参数和公共参数按首字母顺序组装成url查询字符串
(2)StringtoSign:将参数和参数值按照规则编码,构造签名字符串
(3)Signature:使用SHA1算法计算签名字符串的HMAC值,并进行Base64编码,最后得到签名值(Signature
)
(4)发送http请求:将签名值(Signature
)附加到前面的QueryString的最后,向vod api服务器发送请求
注意:通过以上代码看出:在开发过程中如果使用API调用阿里云视频点播步骤繁琐,容易出现问题,一般不用;但是我们也要必须知道,因为现在还是有很多第三方开放开发API,我们使用第三方服务的时候需要使用API调用的;
服务端SDK
2.5.1 简介
sdk的方式将api进行了进一步的封装,不用自己创建工具类。
我们可以基于服务端SDK编写代码来调用点播API,实现对点播产品和服务的快速操作。
2.5.2 功能介绍
- SDK封装了对API的调用请求和响应,避免自行计算较为繁琐的 API签名。
- 支持所有点播服务的API,并提供了相应的示例代码。
- 支持7种开发语言,包括:Java、Python、PHP、.NET、Node.js、Go、C/C++。
- 通常在发布新的API后,我们会及时同步更新SDK,所以即便您没有找到对应API的示例代码,也可以参考旧的示例自行实现调用。
2.5.3 安装
参考文档:https://help.aliyun.com/document_detail/57756.html
添加maven仓库的配置和依赖到pom
<!--使用SDK--> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.3.3</version> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-vod</artifactId> <version>2.15.1</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.2</version> </dependency> |
配置repositories 下载地址
<repositories> <repository> <id>sonatype-nexus-staging</id> <name>Sonatype Nexus Staging</name> <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> |
2.5.4 初始化
参考文档:https://help.aliyun.com/document_detail/61062.html
根据文档示例创建 AliyunVODSDKUtils.java
package com.guli.vod.util;
import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.profile.DefaultProfile;
public class AliyunVODSDKUtils {
public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException { String regionId = "cn-shanghai"; // 点播服务接入区域 DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret); DefaultAcsClient client = new DefaultAcsClient(profile); return client; } } |
2.5.5 测试:获取播放地址!
创建 VodPlayAddressSDK.java
package com.guli.vod; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest; import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse; import com.guli.vod.util.AliyunVODSDKUtils;
import java.util.List;
public class VodPlayAddressSDK {
//账号AccessKey信息请填写(必选) private static String access_key_id = "LTAIjDanEwf9RVXP"; //账号AccessKey信息请填写(必选) private static String access_key_secret = "v23qo8tptfAscACX44QO56XedG5Owk";
/*获取播放地址函数*/ public static GetPlayInfoResponse getPlayInfo(DefaultAcsClient client) throws Exception { GetPlayInfoRequest request = new GetPlayInfoRequest(); request.setVideoId("9b3bda52396641dbb14b71e2409eac1d"); return client.getAcsResponse(request); } /*以下为调用示例*/ public static void main(String[] argv) throws Exception{ DefaultAcsClient client = AliyunVODSDKUtils.initVodClient(access_key_id,access_key_secret); GetPlayInfoResponse response = new GetPlayInfoResponse(); try { response = getPlayInfo(client); List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList(); //播放地址 for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) { System.out.print("PlayInfo.PlayURL = " + playInfo.getPlayURL() + "\n"); } //Base信息 System.out.print("VideoBase.Title = " + response.getVideoBase().getTitle() + "\n"); } catch (Exception e) { System.out.print("ErrorMessage = " + e.getLocalizedMessage()); } System.out.print("RequestId = " + response.getRequestId() + "\n"); } } |
2.5.6 测试:获取播放凭证
创建 VodPlayAuthSDK.java
package com.guli.vod; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest; import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse; import com.guli.vod.util.AliyunVODSDKUtils;
public class VodPlayAuthSDK {
//账号AccessKey信息请填写(必选) private static String access_key_id = "LTAIjDanEwf9RVXP"; //账号AccessKey信息请填写(必选) private static String access_key_secret = "v23qo8tptfAscACX44QO56XedG5Owk";
/*获取播放凭证函数*/ public static GetVideoPlayAuthResponse getVideoPlayAuth(DefaultAcsClient client) throws Exception { GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest(); request.setVideoId("9b3bda52396641dbb14b71e2409eac1d"); return client.getAcsResponse(request); } /*以下为调用示例*/ public static void main(String[] argv) throws Exception{ DefaultAcsClient client = AliyunVODSDKUtils.initVodClient(access_key_id,access_key_secret); GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse(); try { response = getVideoPlayAuth(client); //播放凭证 System.out.print("PlayAuth = " + response.getPlayAuth() + "\n"); //VideoMeta信息 System.out.print("VideoMeta.Title = " + response.getVideoMeta().getTitle() + "\n"); } catch (Exception e) { System.out.print("ErrorMessage = " + e.getLocalizedMessage()); } System.out.print("RequestId = " + response.getRequestId() + "\n"); } } |
标签:return,String,private,publicParams,阿里,static,import,视频点播
来源: https://blog.csdn.net/qq_41230572/article/details/115283845