2.3 抽帧截图 2.4 独立加密 2.5 动图管理 2.6 视频解析 2.7 转封装管理 2.8 配置转码模板 2.9 配置水印模板
2.10 SDK & API对应关系
2.1 开发前准备
本章节介绍了Java SDK的使用说明,您可以参考本章节进行快速集成开发。
开发前准备
● 已完成华为云官网注册,并进行了实名认证。
● 已具备开发环境 ,支持Java JDK 1.8 及其以上版本。
● 已获取华为云账号对应的 Access Key(AK)和 Secret Access Key(SK)。请在 华为云控制台“我的凭证 > 访问密钥”页面上创建和查看您的 AK/SK。具体请参 见访问密钥。
● 已获取转码服务对应区域的项目ID,请在华为云控制台“我的凭证 > API凭证”页 面上查看项目ID。具体请参见API凭证。
● 已将需要处理的媒资文件上传至MPC同区域的OBS桶中,并将OBS桶进行授权,
允许MPC访问。具体请参见上传音视频文件和获取云资源授权。
Maven 安装配置
下载settings.xml文件,覆盖<Maven安装目录>/conf/settings.xml文件即可。如果您不 想覆盖配置文件,可以依次按照下面方法手动修改settings.xml文件。
1. 在profiles节点中添加如下内容:
<profile>
<id>MyProfile</id>
<repositories>
<repository>
<id>HuaweiCloudSDK</id>
<url>https://repo.huaweicloud.com/repository/maven</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>HuaweiCloudSDK</id>
<url>https://repo.huaweicloud.com/repository/maven</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
2. 在mirrors节点中增加:
<mirror>
<id>huaweicloud</id>
<mirrorOf>*,!HuaweiCloudSDK</mirrorOf>
<url>https://repo.huaweicloud.com/repository/maven</url>
</mirror>
3. 增加activeProfiles标签激活配置:
<activeProfiles>
<activeProfile>MyProfile</activeProfile>
</activeProfiles>
4. 配置pom.xml,添加媒体处理的SDK依赖,媒体处理服务具体的SDK版本号请参见
SDK开发中心。
<dependency>
<groupId>com.huaweicloud.sdk</groupId>
<artifactId>huaweicloud-sdk-mpc</artifactId>
<version>3.0.39-rc</version>
</dependency>
开始使用
步骤1 导入依赖模块。
// 用户身份认证
import com.huaweicloud.sdk.core.auth.BasicCredentials;
// 请求异常类
import com.huaweicloud.sdk.core.exception.ClientRequestException;
import com.huaweicloud.sdk.core.exception.ServerResponseException;
// Http 配置
import com.huaweicloud.sdk.core.http.HttpConfig;
// 导入mpc的客户端
import com.huaweicloud.sdk.mpc.v1.MpcClient;
// 导入待请求接口的 request 和 response 类
import com.huaweicloud.sdk.mpc.v1.model.ListTranscodingTaskRequest;
import com.huaweicloud.sdk.mpc.v1.model.ListTranscodingTaskResponse;
// 日志打印
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
步骤2 配置客户端属性。
1. 默认配置。
// 使用默认配置
HttpConfig config = HttpConfig.getDefaultHttpConfig();
2. 代理配置(可选)。
// 使用代理服务器(可选)
config.withProxyHost("http://proxy.huaweicloud.com") .withProxyPort(8080)
.withProxyUsername("test") .withProxyPassword("test");
3. 连接配置(可选)。
// 配置连接超时(可选)
config.withTimeout(3);
4. SSL配置(可选)。
// 配置跳过服务端证书验证(可选)
config.withIgnoreSSLVerification(true);
步骤3 初始化认证信息。
支持两种方式认证,您可以根据实际情况进行选择。
● 使用永久AK/SK
首先需要获取永久AK和SK,以及projectId,您可以参考开发前准备获取。
BasicCredentials credentials = new BasicCredentials() .withAk(ak)
.withSk(sk)
.withProjectId(projectId)
● 使用临时AK/SK
首先需要获取临时AK、SK和SecurityToken,您可以通过token获取或者通过委托 授权获取。
BasicCredentials credentials = new BasicCredentials() .withAk(ak)
.withSk(sk)
.withSecurityToken(securityToken) .withProjectId(projectId)
相关参数说明如下所示:
● ak:华为云账号 Access Key。
● sk:华为云账号 Secret Access Key 。
● projectId:云服务所在区域的项目 ID ,根据你想操作的项目所属区域选择对应 的项目 ID。
● securityToken:采用临时AK/SK认证场景下的安全票据。
步骤4 初始化客户端。
//初始化MPC的客户端
MpcClient MpcClient = MpcClient.newBuilder() .withHttpConfig(config)
.withCredential(credentials) .withEndpoint(endpoint) .build();
endpoint:MPC应用区域和各服务的终端节点,具体请参见地区和终端节点。
步骤5 发送请求并查看响应。
// 初始化请求,以调用查询转码模板接口为例 ListTranscodingTaskResponse response = mpcClient.
listTranscodingTask(new ListTranscodingTaskRequest().withTaskId(Collections.singletonList(1900293L)) ));logger.info(response.toString());
步骤6 异常处理。
表2-1 异常处理
一级分类 一级分类说
明
二级分类 二级分类说明
ConnectionExce
ption 连接类异常 HostUnreachableEx
ception 网络不可达、被拒绝
SslHandShakeExcep
tion SSL认证异常
RequestTimeout
Exception 响应超时异
常 CallTimeoutExcepti
on 单次请求,服务器处理超
时未返回 RetryOutageExcepti
on 在重试策略消耗完成已
后,仍无有效的响应 ServiceResponse
Exception 服务器响应 异常
ServerResponseExce
ption 服务端内部错误,Http响
应码:[500,]
ClientRequestExcep
tion 请求参数不合法,Http响
应码:[400, 500)
// 异常处理 try {
ListTranscodingTaskResponse response= mpcClient.listTranscodingTask(new ListTranscodingTaskRequest().withTaskId(Collections.singletonList(1900293L)));
} catch(ServiceResponseException e) {
logger.error("HttpStatusCode: " + e.getHttpStatusCode());
logger.error("RequestId: " + e.getRequestId());
logger.error("ErrorCode: " + e.getErrorCode());
logger.error("ErrorMsg: " + e.getErrorMsg());
}
步骤7 异步客户端使用。
// 初始化异步客户端
MpcAsyncClient mpcAsyncClient = MpcAsyncClient.newBuilder() .withHttpConfig(config) .withCredential(credentials) .withEndpoint(endpoint) .build();
// 发送异步请求
CompletableFuture<ListTranscodingTaskResponse> future = mpcAsyncClient.listTranscodingTaskAsync(new ListTranscodingTaskRequest().withTaskId(Collections.singletonList(1900293L)));
// 获取异步请求结果
ListTranscodingTaskResponse response = future.get();
logger.info(response.toString());
步骤8 访问日志。
SDK在运行的时候采用了slf4j进行日志打印,如果在运行代码实例时,未配置日志实现 库,会有提示如下:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
您可以根据目标项目实际情况引入对应的日志实现,请在对应的工程项目的 pom.xml 文件中引入日志实现的依赖,如下所示:
● slf4j
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.21</version>
</dependency>
logback
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
● log4j
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
SDK默认会打印访问日志,每次请求都会有一条记录,日志名称为"HuaweiCloud-SDK-Access", 日志格式如下所示:
"{httpMethod} {uri}" {httpStatusCode} {responseContentLength} {requestId}
其中“requestId”是华为云APIG返回的请求ID,可以用于问题跟踪。
可以根据项目情况在对应的日志配置文件中对访问日志进行屏蔽,或者单独打印到独 立文件中。例如在logback中关闭访问日志:
<logger name="HuaweiCloud-SDK-Access" level="OFF"> </logger>
步骤9 原始HTTP侦听器。
在某些场景下可能对业务发出的Http请求进行Debug,需要看到原始的Http请求和返 回信息,SDK提供侦听器功能来获取原始的为加密的Http请求和返回信息。
注意
原始信息打印仅在debug阶段使用,请不要在生产系统中将原始的Http头和Body信息 打印到日志,这些信息并未加密且其中包含敏感数据;当Body体为二进制内容,即 Content-Type标识为二进制时,body为"***",详细内容不输出。
HttpConfig config = new HttpConfig().addHttpListener(HttpListener.forRequestListener(requestListener ->
// 注册侦听器后打印Http Request 原始信息,请勿在生产系统中使用 logger.debug("REQUEST: {} {} {} {}",
requestListener.httpMethod(), requestListener.uri(),
requestListener.headers().entrySet().stream().flatMap(entry ->
entry.getValue().stream().map(value -> entry.getKey() + " : " + value)) .collect(Collectors.joining(";")),
requestListener.body().orElse(""))));
.addHttpListener(HttpListener.forResponseListener(responseListener ->
// 注册侦听器后打印Http Request 原始信息,请勿在生产系统中使用 logger.debug("RESPONSE: {} {} {} {} {}",
responseListener.httpMethod(), responseListener.uri(), responseListener.statusCode(),
responseListener.headers().entrySet().stream().flatMap(entry ->
entry.getValue().stream().map(value -> entry.getKey() + " : " + value)) .collect(Collectors.joining(";")),
responseListener.body().orElse(""))));
MpcClient mpcClient = MpcClient.newBuilder() .withHttpConfig(config)
.withCredential(auth) .withEndpoint(endpoint) .build();
----结束
代码示例 - 初始化 MpcClient
以下示例endpoint为上海2,调用前请根据实际情况填写,并替换如下变量: {your ak string}、{your sk string}、{your endpoint string} 和 {your project id}。
package com.huaweicloud.sdk.test;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.mpc.v1.MpcClient;
public class InitMpc {
private static HttpConfig httpConfig;
private static BasicCredentials auth;
private static String endpoint;
private static MpcClient mpcClient;
public static MpcClient getMpcClient() {
httpConfig = HttpConfig.getDefaultHttpConfig().withIgnoreSSLVerification(true).withTimeout(3);
//http代理设置,请根据实际情况设置
//httpConfig.withProxyHost("xxxxx").withProxyPort(xxxxx).withProxyUsername("xxxxx").
// withProxyPassword("xxxxx");
String ak = "xxxxx";
String sk = "xxxxx";
String projectId = "xxxxx";
endpoint = "https://mpc.cn-east-2.myhuaweicloud.com";
auth = new BasicCredentials().withAk(ak).withSk(sk).withProjectId(projectId);
mpcClient = MpcClient.newBuilder() .withHttpConfig(httpConfig) .withCredential(auth) .withEndpoint(endpoint) .build();
return mpcClient;
} }